Lucence.Net 2.9.3 日期范围搜索
时间:2011-05-10 来源:nasdaqhe
关键步骤如下:
1.将 DateTime 转换成 long 型。 2.索引时要使用 NumericField 进行索引 3.搜索时使用 NumericRangeQuery 进行查询事例代码如下:
[TestMethod()]
public void RangTest(){
RAMDirectory mDirInfo = new RAMDirectory();
IndexWriter mIndexWriter = new IndexWriter(mDirInfo, CAnalyzerLoader.GetAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
mIndexWriter.AddDocument(GetDocumentByModel(1, "姑姑,我是态儿", CDateTime.UNIX_TIMESTAMP(System.DateTime.Now.AddDays(-1))));
mIndexWriter.AddDocument(GetDocumentByModel(2, "B儿,我是态儿", CDateTime.UNIX_TIMESTAMP(System.DateTime.Now.AddDays(-2))));
mIndexWriter.AddDocument(GetDocumentByModel(3, "肝儿,我是态儿", CDateTime.UNIX_TIMESTAMP(System.DateTime.Now.AddDays(-3))));
mIndexWriter.Close();
long upper = CDateTime.UNIX_TIMESTAMP(DateTime.Now.AddDays(-1));
long lower = CDateTime.UNIX_TIMESTAMP(DateTime.Now.AddDays(-3).AddHours(-1));
NumericRangeQuery rangeQuery = NumericRangeQuery.NewLongRange("UpdateOn", lower, upper, true, true);
IndexSearcher mSearcher = new IndexSearcher(mDirInfo, true);
TopDocs topDocs = mSearcher.Search(rangeQuery, 100);
Assert.AreEqual(2, topDocs.totalHits);
}
private Document GetDocumentByModel(int tid,string title,long time)
{
Document doc = new Document();
doc.AddFiled("Id", tid.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)
.AddFiled("Title", title.Trim(), Field.Store.YES, Field.Index.ANALYZED)
.AddLongFiled("UpdateOn", time, Field.Store.NO, true);
return doc;
}
public static Document AddFiled(this Document self, string name, string value, Field.Store fStore, Field.Index fIndex)
{
Field filed = new Field(name, value, fStore, fIndex);
self.Add(filed);
return self;
}
public static Document AddLongFiled(this Document self, string name, long value, Field.Store fStore, bool bIndex)
{
NumericField filed = new NumericField(name, NumericUtils.PRECISION_STEP_DEFAULT, fStore, bIndex).SetLongValue(value);
self.Add(filed);
return self;
}
相关阅读 更多 +