2014-09-22 153 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