简体   繁体   中英

ES Match query analogue in Lucene

I use queries like this one to run in ES:

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

What's the straight analogue for this query in Lucene?

Match Query, as I understand it, basically analyzes the query, and creates a BooleanQuery out of all the terms the analyzer finds. You could get sorta close by just passing the text through QueryParser .

But you could replicate it something like this:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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