1

on the following filter query:

 var searchResults = _client.Search<MyIndexable>(s => s
        .Query(q => q
            .Bool(b => b
                .Must(
                    subQuery => subQuery.QueryString(qs => qs.OnFields(f => f.Title, f => f.Description).Query(searchTerm + "*"")),
                    subQuery => subQuery.Term(f => f.field1, "some string"),
                    subQuery => subQuery.Term(f => f.field2 , "some Guid")))));

I wanted to add each filter below conditinally under Must. like

 if (request.field2)
     ubQuery.Term(f => f.field1, "some string"

can anyone help me to do this?.

2 Answers 2

1

It can be done in Nest. See the code below:

var funcs = new List<Func<QueryDescriptor<MyIndexable>, QueryContainer>>();
funcs.Add(subQuery.QueryString(qs => qs.OnFields(f => f.Title, f => f.Description).Query(searchTerm + "*"")));

if (request.field2) // I believe this is some bool variable
{
    funcs.Add(subQuery => subQuery.Term(f => f.field1, "some string"));
}

funcs.Add(subQuery => subQuery => subQuery.Term(f => f.field2 , "some Guid"));

var searchResults = _client.Search<MyIndexable>(s => s
    .Query(q => q
        .Bool(b => b
            .Must(funcs.ToArray()))));
Sign up to request clarification or add additional context in comments.

4 Comments

bittusarkar, how do I get subQuery instance to add filter Under BoolFilterDescriptor(Must) on the above case ?. like I need to add ExistFilter instead of QueryString and then terms filters conditionally ?
"filter": { "bool": { "must": [ { "exists": { "field": "Cid" } }, { "exists": { "field": "prf" } }, { "term": { "IsActive": true } },
You don't need to define subQuery anywhere. It is part of the Func definition. The code that I've pasted is syntactically correct. You can replace QueryString with any other query you want to implement.
oh..yes I got it. in my case I used FilterDescriptor instead of QueryDescriptor per above json filter string.. and its working fine. Thank you for your help
0

It's difficult for you because of method chaining.

It's more handable to set the configuration in json. Because json is a string, it's simple to break it and insert conditions, etc.

Example:

$config = '{
    "query":
    {';

if (condition) {
    $config .= '"match":
    {
        "foo": "bar"
    }';   
}

$config .= '
    }
}';

Of course, you're free to choose the way to build a json string.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.