# ElasticSearchClient Search function

**URL:** <https://discuss.elastic.co/t/elasticsearchclient-search-function/313290>\
**Category:** Elasticsearch\
**Created:** [August 30, 2022, 8:22pm UTC](https://discuss.elastic.co/t/elasticsearchclient-search-function/313290 "2022-08-30T20:22:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rayyanalbaz1](https://avatars.discourse-cdn.com/v4/letter/r/ac91a4/32.png) [@rayyanalbaz1](https://discuss.elastic.co/u/rayyanalbaz1)\
**Post date:** [August 30, 2022, 8:22pm UTC](https://discuss.elastic.co/t/elasticsearchclient-search-function/313290/1 "2022-08-30T20:22:51Z")

</div>

Hello,

We are trying to implement nested queries like this provided example:

And was wondering if it is possible that we can add the query objects dynamically depending on the number of the query objects created.

For example if I want to search only byName or byMaxPrice or having both of them byName and byMaxPrice. Is there an easier way of adding the query objects to the search function instead of using the if/else statements?

Example:

```auto
if ( name != null ){
          Query byName = MatchQuery.of(m -> m 
               .field("name")
               .query(searchText)
             )._toQuery(); 
}

if( price != null ) {
         Query byMaxPrice = RangeQuery.of(r -> r
             .field("price")
             .gte(JsonData.of(maxPrice)) 
          )._toQuery();
}

**if ( name != null && price != null) {**
SearchResponse<Product> response = esClient.search(s -> s
    .index("products")
    .query(q -> q
        .bool(b -> b 
            **.must(byName)**
**.must(byMaxPrice)**
        )
    ),
    Product.class
);
**} else if ( name != null && price == null ) {**
SearchResponse<Product> response = esClient.search(s -> s
    .index("products")
    .query(q -> q
        .bool(b -> b 
            **.must(byName)** 
        )
    ),
    Product.class
);
**} else if ( name == null && price != null ) {**
SearchResponse<Product> response = esClient.search(s -> s
    .index("products")
    .query(q -> q
        .bool(b -> b 
            **.must(byMaxPrice)** 
        )
    ),
    Product.class
);
}

```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [September 27, 2022, 8:23pm UTC](https://discuss.elastic.co/t/elasticsearchclient-search-function/313290/2 "2022-09-27T20:23:35Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
