【问题标题】:Lucene 4.10 Date Range Query ApiLucene 4.10 日期范围查询 API
【发布时间】:2015-05-01 20:02:19
【问题描述】:

我想在 Lucene 4.10 中以编程方式为日期字段构建一个范围查询,但我没有找到这样做的方法。我的伪代码是:

new DateRangeQuery(dateLowerBound, dateUpperBound);

使用 org.apache.lucene.document.DateTool 类对其进行转换然后使用 NumericRangeQuery 是否是个好主意?

【问题讨论】:

    标签: java date lucene range-query


    【解决方案1】:

    我会选择以下两种可能性之一:

    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,我真的不建议您参与其中。

    【讨论】:

    • 我已经找到了 Solr 的解决方案,但我没有使用它。我怀疑 TermRangeQuery 是正确的。前段时间我记得 Lucene 引入了对日期的优化。我认为第一个解决方案虽然我不确定,但确实适合优化。更糟糕的情况我可以向 Lucene 邮件列表询问。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2019-08-16
    相关资源
    最近更新 更多