# How to combine multiple conditional query in one query

**URL:** <https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033>\
**Category:** Elasticsearch\
**Created:** [February 24, 2024, 12:15pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033 "2024-02-24T12:15:23Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![amrswalha](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/amrswalha/32/132052_2.png) [@amrswalha](https://discuss.elastic.co/u/amrswalha)\
**Post date:** [February 24, 2024, 12:15pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/1 "2024-02-24T12:15:23Z")

</div>

Hello, I'm new to using Elasticsearch. I'm using the .NET client version 8.12, I'm trying to send a query based on parameters. Only add the condition if the parameter value exists. Below is the code for the query:

```
public class ProductSearchDto
{
    public string? Term { get; set; }
    public string? CategoryId { get; set; }
    public int? PriceFrom { get; set; }
    public int? PriceTo { get; set; }
    public int? Stars { get; set; }
    public int Page { get; set; }
    public int PageSize { get; set; }
}

```

The index class:

```
public class ProductIndex 
{
    public string Id { get; set; }
    public decimal Price { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string CategoryId { get; set; }
    public int Stars { get; set; }
    public DateTime IndexedAt { get; set; } = DateTime.UtcNow;
}

```

Also, for the generation of the query below is the code that calls Elasticsearch:

```auto
public async Task<List<ProductIndex>> Search(ProductSearchDto searchDto)
        {
            QueryDescriptor<ProductIndex> query = new QueryDescriptor<ProductIndex>();
            if (!string.IsNullOrEmpty(searchDto.Term))
            {
                 query
                .Match(r => r.Field(y => y.Description).Query(searchDto.Term));
            }
            if (!string.IsNullOrEmpty(searchDto.CategoryId))
            {
                query
               .Match(r => r.Field(y => y.CategoryId).Query(searchDto.CategoryId));
            }
            if (searchDto.Stars.HasValue)
            {
                query
               .Match(r => r.Field(y => y.Stars).Query(searchDto.Stars.Value.ToString()));
            }
            if (searchDto.PriceFrom.HasValue)
            {
                query
               .Range(r => r.NumberRange(z => z.Field(t => t.Price).From(searchDto.PriceFrom)
               .To(searchDto.PriceTo)));
            }
            var result = await _searchOperation.SearchIndexElastic<ProductIndex>
                (query);
            return result;
        }

```

I debugged the query and it always just sending one parameter although other conditions are still active. Any other ways?

---

<div class="post-metadata">

**Author:** ![RabBit\_BR](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/rabbit_br/32/82261_2.png) [@RabBit\_BR](https://discuss.elastic.co/u/RabBit_BR)\
**Post date:** [February 24, 2024, 7:16pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/2 "2024-02-24T19:16:32Z")

</div>

Hi @amrswalha

I don't work with .Net but I believe you need to use [bool query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html) to have more than one clause.

---

<div class="post-metadata">

**Author:** ![amrswalha](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/amrswalha/32/132052_2.png) [@amrswalha](https://discuss.elastic.co/u/amrswalha)\
**Post date:** [February 25, 2024, 7:38am UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/3 "2024-02-25T07:38:19Z")

</div>

Hello @RabBit_BR  
Thanks for the suggestion, tried that and still it sends one query parameter

```auto
public async Task<List<ProductIndex>> Search(ProductSearchDto searchDto)
        {
            Action<QueryDescriptor<ProductIndex>> query = null;
            if (!string.IsNullOrEmpty(searchDto.Term))
            {
                query = q => q
                .Bool(t => t.Must(z => z.Match(r => r.Field(y => y.Description).Query(searchDto.Term))));
            }
            if (!string.IsNullOrEmpty(searchDto.CategoryId))
            {
                query = q => q
                 .Bool(t => t.Must(z => z.Match(r => r.Field(y => y.CategoryId).Query(searchDto.CategoryId))));
            }
            if (searchDto.Stars.HasValue)
            {
                query = q => q
                .Bool(t => t.Must(z => z.Match(r => r.Field(y => y.Stars).Query(searchDto.Stars.Value.ToString()))));
            }
            if (searchDto.PriceFrom.HasValue)
            {
                query = q => q
                .Bool(t => t.Must(z => z.Range(r => r.NumberRange(z => z.Field(t => t.Price).From(searchDto.PriceFrom)
               .To(searchDto.PriceTo)))));
            }
            var result = await _searchOperation.SearchIndexElastic<ProductIndex>
                (query);
            return result;
        }

```

---

<div class="post-metadata">

**Author:** ![RabBit\_BR](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/rabbit_br/32/82261_2.png) [@RabBit\_BR](https://discuss.elastic.co/u/RabBit_BR)\
**Post date:** [February 25, 2024, 3:14pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/4 "2024-02-25T15:14:08Z")

</div>

try this:

```auto
public async Task<List<ProductIndex>> Search(ProductSearchDto searchDto)
{
    Func<QueryContainerDescriptor<ProductIndex>, QueryContainer> query = null;

    if (!string.IsNullOrEmpty(searchDto.Term) || !string.IsNullOrEmpty(searchDto.CategoryId) || searchDto.Stars.HasValue || searchDto.PriceFrom.HasValue || searchDto.PriceTo.HasValue)
    {
        query = q => q.Bool(b =>
        {
            var mustClauses = new List<Func<QueryContainerDescriptor<ProductIndex>, QueryContainer>>();

            if (!string.IsNullOrEmpty(searchDto.Term))
            {
                mustClauses.Add(z => z.Match(r => r.Field(y => y.Description).Query(searchDto.Term)));
            }

            if (!string.IsNullOrEmpty(searchDto.CategoryId))
            {
                mustClauses.Add(z => z.Match(r => r.Field(y => y.CategoryId).Query(searchDto.CategoryId)));
            }

            if (searchDto.Stars.HasValue)
            {
                mustClauses.Add(z => z.Match(r => r.Field(y => y.Stars).Query(searchDto.Stars.Value.ToString())));
            }

            if (searchDto.PriceFrom.HasValue || searchDto.PriceTo.HasValue)
            {
                mustClauses.Add(z => z.Range(r => r.Field(y => y.Price).GreaterThanOrEquals(searchDto.PriceFrom).LessThanOrEquals(searchDto.PriceTo)));
            }

            return b.Must(mustClauses.ToArray());
        });
    }

    var result = await _searchOperation.SearchIndexElastic<ProductIndex>(q => q.Query(query));
    return result;
}

```

---

<div class="post-metadata">

**Author:** ![amrswalha](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/amrswalha/32/132052_2.png) [@amrswalha](https://discuss.elastic.co/u/amrswalha)\
**Post date:** [February 26, 2024, 10:57am UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/5 "2024-02-26T10:57:56Z")

</div>

@RabBit_BR  
Thanks for the support, but still no luck. This code is for an older version of the SDK.

---

<div class="post-metadata">

**Author:** ![RabBit\_BR](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/rabbit_br/32/82261_2.png) [@RabBit\_BR](https://discuss.elastic.co/u/RabBit_BR)\
**Post date:** [February 26, 2024, 12:34pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/6 "2024-02-26T12:34:10Z")

</div>

Try using the must or should clause like this example. I don't know how to adapt to this client but it would probably be the way to the solution.

---

<div class="post-metadata">

**Author:** ![catsupplanetarrabbit](https://avatars.discourse-cdn.com/v4/letter/c/838e76/32.png) [@catsupplanetarrabbit](https://discuss.elastic.co/u/catsupplanetarrabbit)\
**Post date:** [March 25, 2024, 12:01pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/7 "2024-03-25T12:01:40Z")

</div>

I am having the same issue with the newer 8.x client. have you managed to solve it?

---

<div class="post-metadata">

**Author:** ![amrswalha](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/amrswalha/32/132052_2.png) [@amrswalha](https://discuss.elastic.co/u/amrswalha)\
**Post date:** [March 28, 2024, 7:12pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/8 "2024-03-28T19:12:38Z")

</div>

@catsupplanetarrabbit  
Yes, I managed finally to do it, see below code.

I created an object from "SearchRequest" class and filled the "Query" property with && operator with other conditions:

```auto
SearchRequest searchRequest = new SearchRequest();
if (!string.IsNullOrEmpty(searchDto.CategoryId))
{
    searchRequest.Query = searchRequest.Query &&
    new MatchQuery(new Field("categoryId"))
    {
        Query = searchDto.CategoryId
    };
}
if (searchDto.PriceFrom.HasValue)
{
    searchRequest.Query = searchRequest.Query
    && new NumberRangeQuery(new Field("price"))
    {
        From = searchDto.PriceFrom,
        To = searchDto.PriceTo
    };
}
if (searchDto.Stars.HasValue)
{
    searchRequest.Query = searchRequest.Query &&
    new MatchQuery(new Field("stars"))
    {
        Query = searchDto.Stars.ToString()
    };
}
if (!string.IsNullOrEmpty(searchDto.Term))
{
    searchRequest.Query = searchRequest.Query && (
        new QueryStringQuery()
        {
            DefaultField = new Field("description"),
            Query = $"*{searchDto.Term}*"
        }
    ||
        new QueryStringQuery()
        {
            DefaultField = new Field("title"),
            Query = $"*{searchDto.Term}*"
        }
    );

}

```

Hope it helps

---

<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:** [April 25, 2024, 7:13pm UTC](https://discuss.elastic.co/t/how-to-combine-multiple-conditional-query-in-one-query/354033/9 "2024-04-25T19:13:24Z")

</div>

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