Add Match Query Conditionally


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"": {
                                    ""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 ?


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:

                 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.