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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With