2011-03-31 197 views
10

我試着用DateTools.dateToString()方法來索引日期。它適用於索引和搜索。Lucene中的索引和搜索日期

但我已經索引的數據有一些引用是這樣的,它有一個新的索引日期爲Date().getTime()

所以我的問題是,如何對這些數據進行RangeSearch Query ...

任何解決這一???

在此先感謝。

+0

哪個版本的lucene,Lucene <2.9僅執行Lexographic範圍查詢,您可能需要指定確切的日期格式! – Narayan 2011-03-31 05:36:08

+1

我正在使用2.9.1。我是否只需要使用特定的日期格式?它不適用於getTime()嗎? – user660024 2011-04-01 07:04:34

回答

17

您需要在日期字段中使用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); 
    } 
} 
+0

+1總是很高興看到工作代碼 – Bohemian 2011-06-28 04:18:20

3

如果使用NumericField爲你的約會你會得到更好的搜索性能,然後NumericRangeFilter /查詢做到的範圍內搜索。

你只需要將你的日期編碼爲long或int。一種簡單的方法是調用Date的.getTime()方法,但這可能比您需要的分辨率(毫秒)要多得多。如果你只需要一天的時間,你可以將它編碼爲YYYYMMDD整數。

然後,在搜索時間,對您的開始/結束日期進行相同的轉換並運行NumericRangeQuery/Filter。