Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lucene.NET - sorting by int

In the latest version of Lucene (or Lucene.NET), what is the proper way to get the search results back in sorted order?

I have a document like this:

var document = new Lucene.Document();
document.AddField("Text", "foobar");
document.AddField("CreationDate", DateTime.Now.Ticks.ToString()); // store the date as an int

indexWriter.AddDocument(document);

Now I want do a search and get my results back in order of most recent.

How can I do a search that orders results by CreationDate? All the documentation I see is for old Lucene versions that use now-deprecated APIs.

like image 707
Judah Gabriel Himango Avatar asked Apr 21 '10 18:04

Judah Gabriel Himango


1 Answers

After doing some research and poking around with the API, I've finally found some non-deprecated APIs (as of v2.9 and v3.0) that will allow you to order by date:

// Find all docs whose .Text contains "hello", ordered by .CreationDate.
var query = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Text", new StandardAnalyzer()).Parse("hello");
var indexDirectory = FSDirectory.Open(new DirectoryInfo("c:\\foo"));
var searcher = new IndexSearcher(indexDirectory, true);
try
{
   var sort = new Sort(new SortField("CreationDate", SortField.LONG));
   var filter =  new QueryWrapperFilter(query);
   var results = searcher.Search(query, , 1000, sort);
   foreach (var hit in results.scoreDocs)
   {
       Document document = searcher.Doc(hit.doc);
       Console.WriteLine("\tFound match: {0}", document.Get("Text"));
   }
}
finally
{
   searcher.Close();
}

Note I'm sorting the creation date with the LONG comparison. That's because I store the creation date as DateTime.Now.Ticks, which is a System.Int64, or long in C#.

like image 199
Judah Gabriel Himango Avatar answered Oct 01 '22 01:10

Judah Gabriel Himango