Most efficient way to return document with highest DateTime value in field

Tag: Author: panshuying521 Date: 2012-12-02

I have a lucene's index with documents - all of them contain field that stores DateTime value. What would be recommended/most efficient way to extract document with highest value. How it would look like for integer values? Of course i am assuming that values are converted to string using DateTools.DateToString or similar methods.

Other Answer1

Just issue a Query with a Sort descending on your field that contains the Date.

Use a Search method that takes a Sort in parameter, like this one:

IndexSearcher.Search(Query, Filter, int, Sort)

Other Answer2

Elaborating on Jf Beaulac answer, an example of such code may look like the one below. Please note that 'CreatedAt' field is used to store DateTime values.

//providing query that will not filter any documents
var query = new TermRangeQuery("CreatedAt", DateTools.DateToString(DateTime.MinValue, DateTools.Resolution.MINUTE), DateTools.DateToString(DateTime.MaxValue, DateTools.Resolution.MINUTE), false, false);

//providing sorting on 'CreatedAt' and returning just one result
var createdAtSerchResults = searcher.Search(query, null, 1, new Sort(new SortField("CreatedAt", SortField.LONG, true)));

//extracting CreatedAt value from returned document
var documentWithMaxCreatedAt = searcher.Doc(createdAtSerchResults.ScoreDocs.First().Doc);

var result = DateTools.StringToDate(documentWithMaxCreatedAt.Get("CreatedAt"));