Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do bool Queries in ElasticSearch with Java Api?

iam trying to send a bool query against my elasticSearch, that filters out documents. How can i filter boolean expressions like (A AND B AND C) AND (D OR E OR F) AND G with BooleanQueryBuilder Api in Java? I tried with the filter method, but i get no results back. For example:

Imagine A, B, C, D, E, F, G are events where the attribute "name" must match "Robin" for example.

private QueryBuilder getQueryBuilder() {

        BoolQueryBuilder boolQueryBuilder1 = QueryBuilders
                .boolQuery()
                .filter(QueryBuilders.matchQuery(D).operator(Operator.OR))
                .filter(QueryBuilders.matchQuery(E).operator(Operator.OR))
                .filter(F);

        BoolQueryBuilder boolQueryBuilder2 = QueryBuilders
                .boolQuery()
                .filter(QueryBuilders.matchQuery(A).operator(Operator.AND))
                .filter(QueryBuilders.matchQuery(B).operator(Operator.AND))
                .filter(QueryBuilders.matchQuery(C));

        BoolQueryBuilder boolQueryBuilder3 = QueryBuilders
                .boolQuery()
                .filter(G);

        BoolQueryBuilder boolQueryBuilder = QueryBuilders
                .boolQuery()
                .filter(boolQueryBuilder1)
                .filter(boolQueryBuilder2)
                .filter(boolQueryBuilder3);

        return boolQueryBuilder;

}

I know this example is not very good, but i hope u can help me! Thanks!

like image 565
Robatz Rabauke Avatar asked Apr 25 '19 15:04

Robatz Rabauke


1 Answers

Is this one?

private static QueryBuilder getQueryBuilder() {
    //condition
    MatchQueryBuilder A = QueryBuilders.matchQuery("content", "A");
    MatchQueryBuilder B = QueryBuilders.matchQuery("content", "B");
    MatchQueryBuilder C = QueryBuilders.matchQuery("content", "C");
    MatchQueryBuilder D = QueryBuilders.matchQuery("content", "D");
    MatchQueryBuilder E = QueryBuilders.matchQuery("content", "E");
    MatchQueryBuilder F = QueryBuilders.matchQuery("content", "F");
    MatchQueryBuilder G = QueryBuilders.matchQuery("name", "Robin");
    //Maybe you should use TermQuery
    //TermQueryBuilder G = QueryBuilders.termQuery("name", "Robin");


    //1.(A AND B AND C)
    BoolQueryBuilder query1 = QueryBuilders.boolQuery();
    query1.must(A).must(B).must(C);

    //2.(D OR E OR F)
    BoolQueryBuilder query2 = QueryBuilders.boolQuery();
    query2.should(D).should(E).should(F);

    //3.Last
    BoolQueryBuilder lastQuery = QueryBuilders.boolQuery();
    lastQuery.must(query1).must(query2).must(G);
    
    //use filter
    BoolQueryBuilder filterBuiler = QueryBuilders.boolQuery().filter(lastQuery);
    return filterBuiler;
}
like image 156
SuperPirate Avatar answered Nov 11 '22 03:11

SuperPirate