Swar
Swar

Reputation: 182

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 !!

Upvotes: 4

Views: 2138

Answers (2)

bittusarkar
bittusarkar

Reputation: 6357

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()))));

Upvotes: 3

Mohammad Chamanpara
Mohammad Chamanpara

Reputation: 2159

Consider the following code which uses an array of Func s and Values and the way you can use them.

public class TestFunc
{
    public Func<int, Boolean>[] Filters;
    public int[] Values;
    public void Test()
    {
        Filters = new Func<int, bool>[] { Filter1, Filter1, Filter3 };
        Values = new int[] { 1, 2, 3 };

        var result = Filters[0].Invoke(Values[0]);
    }
    Boolean Filter1(int a)
    {
        return a > 0;
    }
    Boolean Filter2(int a)
    {
        return a % 2 == 0;
    }
    Boolean Filter3(int a)
    {
        return a != 0;
    }

}

I hope this would be helpful.

Upvotes: 0

Related Questions