Lucene中的ES Match查询模拟

时间:2019-04-02 14:45:43

标签: elasticsearch lucene full-text-search

我使用类似这样的查询在ES中运行:

boolQuery.must(QueryBuilders.matchQuery("field", value).minimumShouldMatch("50%"))

在Lucene中,此查询的直接模拟是什么?

1 个答案:

答案 0 :(得分:1)

据我了解,

匹配查询基本上是对查询进行分析,并从分析器找到的所有条件中创建一个布尔查询。您只需将文本通过QueryParser即可获得 sorta

但是您可以复制如下内容:

public static Query makeMatchQuery (String fieldname, String value) throws IOException { 
    //get a builder to start adding clauses to.
    BooleanQuery.Builder qbuilder = new BooleanQuery.Builder();

    //We need to analyze that value, and get a tokenstream to read terms from
    Analyzer analyzer = new StandardAnalyzer();
    TokenStream stream = analyzer.tokenStream(fieldname, new StringReader(value));
    stream.reset();

    //Iterate the token stream, and add them all to our query
    int countTerms = 0;
    while(stream.incrementToken()) {
        countTerms++;
        Query termQuery = new TermQuery(new Term(
                fieldname, 
                stream.getAttribute(CharTermAttribute.class).toString()));
        qbuilder.add(termQuery, BooleanClause.Occur.SHOULD);
    }
    stream.close();
    analyzer.close();

    //The min should match is a count of clauses, not a percentage. So for 50%, count/2
    qbuilder.setMinimumNumberShouldMatch(countTerms / 2);
    Query finalQuery = qbuilder.build();
    return finalQuery;
}