# Add Match Query Conditionally

**URL:** <https://discuss.elastic.co/t/add-match-query-conditionally/198541>\
**Category:** Elasticsearch\
**Created:** [September 8, 2019, 7:10am UTC](https://discuss.elastic.co/t/add-match-query-conditionally/198541 "2019-09-08T07:10:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![vikasnew](https://avatars.discourse-cdn.com/v4/letter/v/bcef8e/32.png) [@vikasnew](https://discuss.elastic.co/u/vikasnew)\
**Post date:** [September 8, 2019, 7:10am UTC](https://discuss.elastic.co/t/add-match-query-conditionally/198541/1 "2019-09-08T07:10:59Z")

</div>

Hello,

i am in caught a situation where i need to apply a match query based on a condition.

my code is as below:

```
var searchResponse = await client.SearchAsync<StringResponse>("custom-index", @"
            {
                ""from"": " + entity.Offset + @",
                ""size"": " + entity.Count + @",
                ""query"": {
                    ""bool"":{
                        ""must"":[{
                                    ""match"": { ""fields.category"": """ + entity.Category + @""" }
                                 }]
                            }
                        }
                }");

```

i need to add match condition only when "entity.Category" is not null or empty.

how can i achieve this ?

Thanks

---

<div class="post-metadata">

**Author:** ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)\
**Post date:** [September 13, 2019, 3:13pm UTC](https://discuss.elastic.co/t/add-match-query-conditionally/198541/2 "2019-09-13T15:13:51Z")

</div>

If I understand it correctly the logic you want is "empty field. or specific value".

The "OR" in that sentence suggests you should have a top-level `bool` query with a `should` array for the options. The psuedo code is this:

```
bool
     should 
        bool
            must_not
                 exists query for field `category`
        match query for category: foo

```

So the match query is ORed with a does-not-exist clause.

---

<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:** [October 11, 2019, 3:13pm UTC](https://discuss.elastic.co/t/add-match-query-conditionally/198541/3 "2019-10-11T15:13:52Z")

</div>

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