javaspring-bootelasticsearchquery-builderelasticsearch-high-level-restclient

How to search using multiple fields in Elastic Search through Java high level rest client


I'm new to Elastic search. Successfully implemented search document API for matching single field like below:

SearchRequest searchRequest = new SearchRequest(indexName);

//Single field match, only for documentId
QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("documentId", documentId); 

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(matchQueryBuilder);
searchRequest.source(sourceBuilder);

SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

I wanna filter data using multiple fields in single API, for Example, need to add more filters in above API as per below condition:

documentNumber > 66 &&  (documentCreatedDate >= date1 && documentCreatedDate <= date2) && documentName like "%test%"

Can anyone please help how to apply all these filters in a single SearchRequest?


Solution

  • You can use rangeQuery as specified in docs:

    QueryBuilders.rangeQuery("documentNumber")                                             
        .gte(66); 
    
    QueryBuilders.rangeQuery("documentCreatedDate")                                             
        .gte(date1)
        .lt(date2); 
    

    For patterns you can use wildcardQuery:

    wildcardQuery(
            "documentName",                                              
            patternString); 
    

    From Docs:
    Find documents where the field specified contains terms which match the pattern specified, where the pattern supports single character wildcards (?) and multi-character wildcards (*)

    For applying multiple filters in single query, please refer to this answer.