Add Match Query Conditionally

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

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.

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