[英]Indexing and Searching Date in Lucene
我試着用DateTools.dateToString()
方法索引日期。 它適用於索引和搜索。
但是我已經索引的數據有一些引用,它將Date作為一個新的Date().getTime()
索引。
所以我的問題是如何對這些數據執行RangeSearch Query
...
任何解決方案???
提前致謝。
您需要在日期字段上使用TermRangeQuery
。 該字段始終需要使用DateTools.dateToString()
編制索引才能正常工作。 以下是使用Lucene 3.0對日期范圍進行索引和搜索的完整示例:
public class LuceneDateRange {
public static void main(String[] args) throws Exception {
// setup Lucene to use an in-memory index
Directory directory = new RAMDirectory();
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
MaxFieldLength mlf = MaxFieldLength.UNLIMITED;
IndexWriter writer = new IndexWriter(directory, analyzer, true, mlf);
// use the current time as the base of dates for this example
long baseTime = System.currentTimeMillis();
// index 10 documents with 1 second between dates
for (int i = 0; i < 10; i++) {
Document doc = new Document();
String id = String.valueOf(i);
String date = buildDate(baseTime + i * 1000);
doc.add(new Field("id", id, Store.YES, Index.NOT_ANALYZED));
doc.add(new Field("date", date, Store.YES, Index.NOT_ANALYZED));
writer.addDocument(doc);
}
writer.close();
// search for documents from 5 to 8 seconds after base, inclusive
IndexSearcher searcher = new IndexSearcher(directory);
String lowerDate = buildDate(baseTime + 5000);
String upperDate = buildDate(baseTime + 8000);
boolean includeLower = true;
boolean includeUpper = true;
TermRangeQuery query = new TermRangeQuery("date",
lowerDate, upperDate, includeLower, includeUpper);
// display search results
TopDocs topDocs = searcher.search(query, 10);
for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
Document doc = searcher.doc(scoreDoc.doc);
System.out.println(doc);
}
}
public static String buildDate(long time) {
return DateTools.dateToString(new Date(time), Resolution.SECOND);
}
}
如果您使用NumericField作為日期,然后使用NumericRangeFilter / Query進行范圍搜索,您將獲得更好的搜索性能。
您只需將日期編碼為long或int。 一種簡單的方法是調用Date的.getTime()方法,但這可能比你需要的分辨率(毫秒)要多得多。 如果您只需要一天,您可以將其編碼為YYYYMMDD整數。
然后,在搜索時,在開始/結束日期進行相同的轉換並運行NumericRangeQuery / Filter。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.