Search code examples
c#.netelasticsearchnest

How to add conditional expressions while querying Elastic Search?


I want to know if we can write conditional expressions while fetching data from elastic search.

For example - There is a column in the records that I have. The column has integer values from 1 to 100. I want to fetch all such records where that column has even value. Currently, I am doing it like this, building a list of values that I want and then passing them in TermsQuery :

 for(int i = 1; i <= 100; i++)
        {
            if (i%2 == 0)
                possibleMatches.Add(i);
        }

        Func<TermsQueryDescriptor<MyClass>, ITermsQuery> TermsQuery = t =>
        {
            return t.Field(f => f.MyColumn).Terms(possibleMatches);
        };

        var results = collection.Search(s =>
                      s.Index(MyIndex).Type(MyElasticsearchType)
                     .Query(qu=>qu.Terms(TermsQuery));

Is it possible to write a conditional expression in Terms query or some other query type ? Say something like

t.Field(f=> f.MyColumn%2 == 0)

Solution

  • It's not possible to write conditional expressions in the way suggested. You have two choices here:

    1. Use a script query and write the condition in the Painless scripting language
    2. Index whether MyColumn value is odd or even into a separate field.

    The first approach is more flexible, whilst the second approach will perform better.