用于通配符查询的Apache Lucene createWeight()

时间:2017-08-15 11:57:50

标签: java apache lucene

我正在使用Apache Lucene 6.6.0而我正在尝试从搜索查询中提取术语。当前版本的代码如下所示:

Query parsedQuery = new AnalyzingQueryParser("", analyzer).parse(query);
Weight weight = parsedQuery.createWeight(searcher, false);
Set<Term> terms = new HashSet<>();
weight.extractTerms(terms);

它工作得非常好,但最近我注意到它不支持使用通配符查询(即*符号)。如果查询包含通配符,那么我得到一个例外:

  

java.lang.UnsupportedOperationException:Query   id:123 * 456未实现createWeight   org.apache.lucene.search.Query.createWeight(Query.java:66)at   org.apache.lucene.search.IndexSearcher.createWeight(IndexSearcher.java:751)     在   org.apache.lucene.search.BooleanWeight。(BooleanWeight.java:60)     在   org.apache.lucene.search.BooleanQuery.createWeight(BooleanQuery.java:225)

那么有没有办法将createWeight()用于通配符查询?或者可能还有其他方法可以在没有createWeight()的情况下从查询中提取搜索字词?

1 个答案:

答案 0 :(得分:1)

长话短说,有必要重写查询,例如,如下:

final AnalyzingQueryParser analyzingQueryParser = new AnalyzingQueryParser("", analyzer);

// TODO: The rewrite method can be overridden.
// analyzingQueryParser.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_REWRITE);

Query parsedQuery = analyzingQueryParser.parse(query);
// Here parsedQuery is an instance of the org.apache.lucene.search.WildcardQuery class.

parsedQuery = parsedQuery.rewrite(reader);
// Here parsedQuery is an instance of the org.apache.lucene.search.MultiTermQueryConstantScoreWrapper class.

final Weight weight = parsedQuery.createWeight(searcher, false);
final Set<Term> terms = new HashSet<>();
weight.extractTerms(terms);

请参阅主题:

了解更多详情。

似乎提到的Stack Overflow问题就是这个问题:How to get matches from a wildcard Query in Lucene 6.2