Lambda query in NEST elastic search contains an array of filters and values

Of the two arrays Filter [] and Value [], which contain filter names and filter values

I need to create a dynamic lambda query applying an array of filters and values ​​to it.

Something similar to this, but for dynamically applying all values ​​in an array.

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

      

Waiting for a suitable answer!

+3


source to share


2 answers


You need to create a filter Bool Should

and pass an array of objects FilterContainer

that can be dynamically generated. I wrote a small piece of code that will build the Nest request according to 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()))));

      

+3


source


Consider the following code, which uses the Func s and Values ​​array and how to 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;
    }

}

      



Hope this would be helpful.

0


source







All Articles