我不确定我如何使用它进行排序。我希望按日期时间降序对结果进行排序。
答案 0 :(得分:7)
UPDATE (2013.04.22):较新版本的Lucene.NET允许更直接地按DateTime排序,例如:
var sort = new Sort( new SortField( Constants.LuceneCreationTime, SortField.LONG, true ) );
var filter = new QueryWrapperFilter( query );
var docs = searcher.Search( query, filter, 100, sort )
将CreationTime添加为DateTime.Ticks以允许通过SortField.LONG进行搜索。
我已经使用3.0版进行了测试。
在常规Lucene社区中,建议拆分DateTime以使其具有足够的性能和/或足够精确(Int32只有10个字符)。半年前我用最多500,000个文档进行了基准测试,而且我记得,这确实是我能想出的唯一一种高效的方式。
无论如何,你可以尝试这样的事情:
<强>索引强>
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);
<强>搜索强>
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>();
}
}