简体   繁体   中英

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?

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

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