views:

147

answers:

1

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.

+1  A: 

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("CreationTime", 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#.

Judah Himango