javaelasticsearchelastic-stackelasticsearch-jest

Jest elastic search Query builder query with multiple match strings


I am trying to query elastic search in Java using Jest. I am using a query builder to construct the query.

QueryBuilder matchQuery = QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery("id", "3434"))
            .must(QueryBuilders.matchQuery("name", "name"))
            .must(QueryBuilders.matchQuery("action", "login"))
            .must(rangeQuery);

 //i have this map now 
 Map<String , String> parameters = new HashMap<>();
    parameters.put("id", "3433");
    parameters.put("name", "name");
    parameters.put("action", "login");

It would be great if some one can tell me if this can be constructed dynamically , like the matchQueries. For instance i would have three match queries , but i would have more. I can put my match query attributes in a Map. But if i iterate that how would we can define this boolQuery ? Anyone has any idea on this ?

Looking for something like this

 QueryBuilder matchQuery = QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery(map.key, map.value))

            .must(rangeQuery);

but how would i contruct this dynamically ?


Solution

  • You can simply iterate over your map and add each condition to the query, like this:

    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();    
    for(String key : parameters.keySet()){
      boolQuery.must(QueryBuilders.matchQuery(key, parameters.get(key)));
    }
    boolQuery.must(rangeQuery);