首页 > 解决方案 > 如何在 Apache Lucene 中将 PhraseQuery 与 RangeQuery 结合使用?

问题描述

基本上,我希望能够使用以下查询来查询索引"phrase query" AND date:[20180101 TO 20181231]。我尝试使用MultiFieldQueryParser,但出现以下错误:

Exception in thread "main" java.lang.IllegalStateException: field "date" was indexed without position data; cannot run PhraseQuery

所以我使用如下代码构造了查询:

final Query phraseQ = new QueryParser("text", Analyzer.CUSTOM)
        .parse(query);
final Query rangeQ = new QueryParser("date", Analyzer.CUSTOM)
        .parse(dateRange);

final Query q = new BooleanQuery.Builder()
        .add(phraseQ, BooleanClause.Occur.MUST)
        .add(rangeQ, BooleanClause.Occur.MUST)
        .build();

其中查询是"phrase query"~1和 dateRange 是date:[20180101 TO 20181231]。我仍然得到以下异常

Exception in thread "main" java.lang.IllegalStateException: field "date" was indexed without position data; cannot run PhraseQuery (phrase=date:"phrase query"~1)

虽然我不使用短语查询日期字段。

短语查询是否可以与范围查询相结合?

标签: javalucene

解决方案


MultiFieldQueryParser 旨在搜索在查询中未指定字段时给出的所有字段列表。所以这:

MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[] {"text","date"}, new StandardAnalyzer());
Query query = parser.parse("\"phrase query\" AND date:[20180101 TO 20181231]");

生成如下所示的查询:

+(text:"phrase query" date:"phrase query") +date:[20180101 TO 20181231]

因此问题。如果您仅将其替换为标准QueryParser,并将“文本”作为默认字段,它应该会产生您想要的内容。


但是,就您提供的代码而言,它看起来不错。尝试dateRange在解析之前打印它的内容,确保它是你认为的那样。


推荐阅读