Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How build dynamic query elasticsearch

I would like to build a query to elasticsearch using search criteria from a html form. I have several input fields on the html page. For example, if the user fill two of these fields I could write :

    BoolQueryBuilder query =  QueryBuilders.boolQuery()
                                .must(QueryBuilders.termQuery("archivo", "archivo1"))
                                .must(QueryBuilders.termQuery("nombre", "documento1"));  

But... what if the user fill three fields I could have :

    BoolQueryBuilder query =  QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("archivo", "archivo1"))
                        .must(QueryBuilders.termQuery("nombre", "documento1"))
                        .must(QueryBuilders.termQuery("third", "test"));

Is there any way to dinamicall build this kind of queries?

like image 522
Víctor Avatar asked Mar 13 '23 14:03

Víctor


1 Answers

BoolQueryBuilder.must() adds a predicate, it does not replace the previous one.

Therefore, suppose that the value of the field archivo is in the variable inputArchivo and so on, you can check if the field is filled then add the predicate :

 BoolQueryBuilder query = QueryBuilders.boolQuery();
 if(inputArchivo != null && !inputArchivo.isEmpty()) {
   query.must(QueryBuilders.termQuery("archivo", inputArchivo));
 }

 if(inputNombre != null && !inputNombre.isEmpty()) {
   query.must(QueryBuilders.termQuery("nombre", inputNombre));
 }

 if(inputThird != null && !inputThird.isEmpty()) {
   query.must(QueryBuilders.termQuery("third", inputThird));
 }

and yet if you don't know what terms will came you can iterate over a HashMap with the values:

for (Map.Entry<String, Object> entry : map.entrySet()) {
    query.must(QueryBuilders.termQuery(entry.getKey, entry.getValue))
}
like image 189
Arnaud Denoyelle Avatar answered Mar 20 '23 23:03

Arnaud Denoyelle