I am using the new version 8.13 of Elasticsearch for a new search app and trying to imitate the below kind of logic using the new Java API client instead of using Java High Level Rest client which was deprecated now. I have to perform search from multiple indices including below queries-
1.multiple matchPhrasePrefixQuery like below
BoolQueryBuilder searchTheseFields = QueryBuilders.boolQuery();
for (String searchFields : searchTheseFieldsArray) {
searchTheseFields .should(QueryBuilders.matchPhrasePrefixQuery(searchFields, **SearchText**));
}
2.multiple term queries with fileds and values
BoolQueryBuilder filterFields = QueryBuilders.boolQuery();
for (Map.Entry<String, Object> entry : filterTheseFields.entrySet()) {
filterFields.must(QueryBuilders.termQuery(entry.getKey(), entry.getValue()));
}
- multiple range queries
BoolQueryBuilder rangeFilter1 = QueryBuilders.boolQuery();
BoolQueryBuilder rangeFilter2 = QueryBuilders.boolQuery();
rangeFilter1.should(QueryBuilders.rangeQuery(key).gte("gteVal").lte("lteVal"))
.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery(key)));
And finally add all these queries to a single Query Builder like below and call using client.
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
.must(searchTheseFields)
.must(filterFields)
.filter(rangeFilter1);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder);
searchSourceBuilder.from(data.getFrom());
searchSourceBuilder.size(data.getSize());
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(passing indices here);
searchRequest.source(searchSourceBuilder);
SearchResponse response = client.search(searchRequest);