Lucene.NET - sorting by int

十年热恋 提交于 2019-12-18 11:56:29

问题


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:


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#.



来源:https://stackoverflow.com/questions/2685490/lucene-net-sorting-by-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!