简体   繁体   English

Lucene 4.10日期范围查询Api

[英]Lucene 4.10 Date Range Query Api

I want to build a range query for a date field programmatically in Lucene 4.10, but I didn't find anyway to do that. 我想在Lucene 4.10中以编程方式为日期字段构建范围查询,但是我却没有找到这样做的方法。 My pseudocode would be: 我的伪代码是:

new DateRangeQuery(dateLowerBound, dateUpperBound);

Is it a good idea to use org.apache.lucene.document.DateTool class to transform it and then use a NumericRangeQuery ? 使用org.apache.lucene.document.DateTool类转换它然后使用NumericRangeQuery是一个好主意吗?

I'd pick one of two possibilities: 我选择以下两种可能性之一:

1 - Use DateTools to obtain a string representation good for indexing: 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 - Skip date tools, and index the dates as numeric values using Date.getTime() or Calendar.getTimeInMillis() , or something similar: 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());

I'd generally opt for the first, as it makes control over precision more obvious, but whichever strikes your fancy should work fine. 我通常会选择第一个,因为它可以使对精度的控制更加明显,但是无论您选择哪种效果都可以。

Also worth mentioning is solr's TrieDateField , though I wouldn't really recommend getting into that if you aren't already using solr anyway. 同样值得一提的是solr的TrieDateField ,尽管如果您还没有使用solr,我不建议您这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM