Reputation:
I am unsure that how I can use it with sorting. I want to sort the result by datetime descending.
Upvotes: 3
Views: 7427
Reputation: 1000
UPDATE (2013.04.22): Newer versions of Lucene.NET allow sorting by DateTime more directly, for example:
var sort = new Sort( new SortField( Constants.LuceneCreationTime, SortField.LONG, true ) );
var filter = new QueryWrapperFilter( query );
var docs = searcher.Search( query, filter, 100, sort )
Add the CreationTime as DateTime.Ticks to allow searching for it via SortField.LONG.
I have tested this with version 3.0.
yes, this question has partly been answered before. However, I would like to add a note on the DateTime part.
In regular Lucene communities it is offen recommended to split up DateTime's in order to make them performant and/or precise enough (Int32 is just 10 characters). I've benchmarked with up to 500.000 documents half a year ago, and as I remember, this really was the only performant way I could come up with.
Anyway, you can try out something like this:
Indexing
var indexWriter = OpenWritableIndex();
Document doc = new Document();
DateTime lastEdited = DateTime.Now;
int year = lastEdited.Year;
int month = lastEdited.Month;
int day = lastEdited.Day;
int hour = lastEdited.Hour;
int minute = lastEdited.Minute;
doc.Add(new Field("LastEditedYear", year.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.Add(new Field("LastEditedMonth", month.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.Add(new Field("LastEditedDay", day.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.Add(new Field("LastEditedHour", hour.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.Add(new Field("LastEditedMinute", minute.ToString(), Field.Store.YES, Field.Index.UN_TOKENIZED));
indexWriter.AddDocument(doc);
Searching
var readableIndex = OpenReadableIndex();
var searcher = new IndexSearcher(readableIndex.Directory);
var multiParser = new MultiFieldQueryParser(termsToSearchIn, readableIndex.Analyzer);
var query = multiParser.Parse(terms);
Hits hits = null;
Sort sort = new Sort(new SortField[]
{
new SortField("LastEditedYear", true),
new SortField("LastEditedMonth", true),
new SortField("LastEditedDay", true),
new SortField("LastEditedHour", true),
new SortField("LastEditedMinute", true)
});
if(sort != null)
{
try
{
hits = searcher.Search(query, sort);
}
catch(SystemException) // Lucene throws a SystemException when trying to sort an empty response.
{
return new List<string>();
}
}
Upvotes: 7