How can i create a dynamic QueryContainer with many QueryContainerDescriptor?
How to dynamically build up a Bool query using the NEST client?

I will teach you how to create a dynamic nest query with and logic.

You must to write your QueryContainer:

QueryContainer filters_complete = null;

Then we must to attach to them the many filters that we want

var dateFilter = new QueryContainerDescriptor<OBJTYPE>().DateRange(t => t.Field("student.age").GreaterThanOrEquals(DateTime.Min).LessThanOrEquals(DateTime.Max));
filters_complete &= (new QueryContainerDescriptor<OBJTYPE>().Nested(n => n.Path("student").Query(q2 => q2.Bool(bq => bq.Filter(dateFilter)))));

Add in and another filter to out QueryContainer. Just need to create the other QueryContainerDescriptor

var partial = new QueryContainerDescriptor<OBJTYPE>().Range(t => t.Field("school.alumn_number").GreaterThan(0));
filters_complete &= (new QueryContainerDescriptor<OBJTYPE>().Nested(n => n.Path("school").Query(q2 => q2.Bool(bq => bq.Filter(partial)))));

We have created a query to extract: (student with age >= XX && age <= YY) && (school with alumn number > 0)

Now we must to use it:

string _urlServerElasticSearch = WebConfigurationManager.AppSettings["ElasticSearch_Server"];
var node = new Uri(_urlServerElasticSearch);
var client = new ElasticClient(node);

var response1 = client.Search<OBJTYPE>(s => s
.Index("index")
.Type("mapping")
.Query(_ => filters_complete).Scroll("60s").From(0).Size(100)
);

Use the _ in the lambda expressions, because we don’t care about the parameter!
I use the Scroll() method in my query, if you want to know how to manage the Scroll, see this guide.

 

Do you know a simplest method?
There is some error in my article?
Or if you have a question write me!