Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda query in NEST elastic search to have array of filters and values

From two arrays Filter[] and Value[] which hold filter names and filter values

I need to generate a dynamic lambda query applying array of filters and values on it.

Something similar to this, but to apply all array values dynamically.

var searchResults = client.Search<Job>(s => s.Type("job")
                               .Size(size)
                               .Filter(f =>
                               f.Term(Filter[0], Value1[0]) ||
                               f.Term(Filter[1], Value[1]))
                              );

Awaiting a suitable answer !!

like image 967
Swar Avatar asked Sep 02 '25 04:09

Swar


1 Answers

You need to create a Bool Should filter and pass an array of FilterContainer objects which can be generated dynamically. I've written a small code snippet that will build the Nest query as per your requirements.

var Filter = new List<string> { "field1", "field2" };
var Value = new List<string> { "value1", "value2" };

var fc = new List<FilterContainer>();
for (int i = 0; i < 2 /* Size of Filter/Value list */; ++i)
{
    fc.Add(Filter<string>.Term(Filter[i], Value[i]));
}

var searchResults = client.Search<Job>(s => s
    .Type("job")
    .Size(size)
    .Filter(f => f
        .Bool(b => b
            .Should(fc.ToArray()))));
like image 149
bittusarkar Avatar answered Sep 05 '25 01:09

bittusarkar