Search code examples
javaelasticsearchodatafiltering

Need to implement a Elastic search query with both $select and $filter


I have a Odata Query : /ecommerceadmin/ODataService.svc/search?$select=status&$filter=id eq 'test.com'and name eq 'abc'

How can I implement the code in elastic search to get the data accordingly.What method in SearchSourceBuilder should be used?


Solution

  • You can probably easily get away with one match and one term query like this:

    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.index.query.QueryBuilders.*;
    
    BoolQueryBuilder query = QueryBuilders.boolQuery()
        .must(QueryBuilders.matchQuery("name", "abc"))       // 1.
        .filter(QueryBuilders.termQuery("id", "test.com"));  // 2.
    
    SearchResponse response = client.prepareSearch("ecommerce_index")
            .setTypes("ecommerce_type")
            .setQuery(query)
            .setFetchSource(new String[]{"status"}, null)    // 3.
            .setFrom(0)
            .setSize(10)
            .execute()
            .actionGet();
    

    In the above code:

    1. takes care of the name eq 'abc' $filter
    2. takes care of the id eq 'test.com' $filter
    3. takes care of the $select=status part