Home > Enterprise >  How to use Conditionals in NEST Queries Elasticsearch
How to use Conditionals in NEST Queries Elasticsearch

Time:03-22

I want to build a NEST query for Elasticsearch depending on the user input with an If Else statement. At the moment it only accepts one condition in the must part and the other one isn't added to the query.

The following code compiles to this http request:

{"from":0,"query":{"bool":{"must":[{"nested":{"path":"customer","query":{"term":{"customer.customerId":{"value":1}}}}}]}},"size":10}

as you can see the SearchPersonId isn't added into the must condition.

The search method:

private ISearchResponse<Country> GetFilteredResults(ElasticClient client, Query query)
{
    var searchRequest = new SearchDescriptor<Country>();
    searchRequest.From(0).Size(10).Query(q =>
    {
        q.Bool(b => b
            .Must(mc =>
            {
                if (query.CustomerId != 0) mc.SearchCustomerId(query.CustomerId);
                if (query.PersonId != 0) mc.SearchPersonId(query.PersonId);
                
                return mc;
            })
        );

        return q;
    });

    return client.Search<Country>(searchRequest);
}

The query methods:

public static class Helpers
{
    public static QueryContainer SearchPersonId(this QueryContainerDescriptor<Country> container, string personId)
    {
        return container
            .Nested(n => n
                .Path(p => p.Person)
                .Query(q => q
                    .Term(t => t
                        .Field(f => f.Person.PersonId).Value(personId))));
    }

    public static QueryContainer SearchCustomerId(this QueryContainerDescriptor<Country> container, string customerId)
    {
        return container
            .Nested(n => n
                .Path(p => p.Customer)
                .Query(q => q
                    .Term(t => t
                        .Field(f => f.Customer.CustomerId).Value(customerId))));
    }
}

CodePudding user response:

One of the overloads of Must method accepts array of QueryContainer which can help you implement conditional logic

ISearchResponse<Country> GetFilteredResults(ElasticClient client, Query query)
{
    var queryContainers = new List<QueryContainer>();
    var descriptor = new QueryContainerDescriptor<Country>();
    if (query.CustomerId != 0) queryContainers.Add(descriptor.SearchCustomerId(query.CustomerId));
    if (query.PersonId != 0) queryContainers.Add(descriptor.SearchPersonId(query.PersonId));
    var searchRequest = new SearchDescriptor<Country>();
    searchRequest.From(0).Size(10).Query(q => q.Bool(b => b.Must(queryContainers.ToArray())));

    return client.Search<Country>(searchRequest);
}
  • Related