Elastic search nest dynamic query with object initializer NEST 5.x
But it doesnt work cause Field class doesnt accept type arguments.
You need to ensure that you include a using static directive for Nest.Infer
i.e.
using static Nest.Infer;
with the rest of the using directives.
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
No need to wrap in a Must()
, just do
.Query(q => q.MatchAll() && andQuery)
which will wrap both queries in a bool
query must
clause. You also don't need to null
check andQuery
because NEST is smart enough to not combine the two queries if either or both are null
.
if (!string.IsNullOrEmpty(queries.queryfields)){ var val = queries.queryfields; TermQuery tq = new TermQuery { Field = queries.queryfields, Value = val }; if (andQuery == null) andQuery = tq; else andQuery &= tq; //QueryContainers.Add(tq);}
NEST has the concept of conditionless queries so you don't need to check it queries.queryfields
is null or empty, simply build the query and add it to andQuery
. So it would become
var val = queries.queryfields;andQuery &= new TermQuery{ Field = queries.queryfields, Value = val};
Aside
All of the NEST documentation is generated from source code; you can trace back to the original source file by clicking on any edit link within the documentation. This will take you to a github page, such as this one for bool queries. From here, the document contains an important note that links back to the original source.