2014-09-22 50 views
1

我想在Lucene 4.10中以編程方式爲日期字段構建一個範圍查詢,但是我沒有找到這樣做。我的僞代碼將是:Lucene 4.10日期範圍查詢Api

new DateRangeQuery(dateLowerBound, dateUpperBound); 

是否使用org.apache.lucene.document.DateTool類改造它,然後使用NumericRangeQuery一個好主意?

回答

2

我會選擇兩種可能性之一:

1 - 使用DateTools獲得字符串表示良好的索引:

String indexableDateString = DateTools.dateToString(theDate, DateTools.Resolution.MINUTE); 
doc.add(new StringField("importantDate", indexableDateString, Field.Store.YES)); 
... 
TopDocs results = indexSearcher.search(new TermRangeQuery(
    "importantDate", 
    new BytesRef(DateTools.dateToString(lowDate, DateTools.Resolution.MINUTE)), 
    new BytesRef(DateTools.dateToString(highDate, DateTools.Resolution.MINUTE)), 
    true, 
    false 
)); 
... 
Field dateField = resultDocument.getField("importantDate") 
Date retrievedDate = DateTools.stringToDate(dateField.stringValue()); 

2 - 跳到最新的工具和指標的日期爲數值使用Date.getTime()Calendar.getTimeInMillis(),或類似的東西:

long indexableDateValue = theDate.getTime(); 
doc.add(new LongField("importantDate", indexableDateValue, Field.Store.YES)); 
... 
TopDocs results = indexSearcher.search(NumericRangeQuery.newLongRange(
    "importantDate", 
    lowDate.getTime(), 
    highDate.getTime(), 
    true, 
    false 
)); 
... 
Field dateField = resultDocument.getField("importantDate") 
Date retrievedDate = new Date(dateField.numericValue()); 

我一般會選擇第一個,因爲它使控制權精度更明顯,但無論哪一種都會讓你感覺不錯。

另外值得一提的是solr的TrieDateField,儘管如果你還沒有使用solr,我不會推薦你進入。

+0

我已經找到了Solr的解決方案,但我沒有使用它。 TermRangeQuery,我猜是正確的。前些日子我記得Lucene引入了日期優化。我認爲第一個解決方案雖然我不確定,但它適合優化。更糟糕的情況下,我可以問問Lucene的郵件列表。謝謝 – pokeRex110 2014-09-23 07:43:53