How to append two SearchDescriptors in NEST

1.8k views Asked by At

I am taking input from a client to build up an elasticsearch query using NEST. I start out with the basics, like so:

var search = esClient.Search<MyData>(s => s
    .From(pageNum * pageSize)
    .Take(pageSize)
    .QueryRaw(@"{""match_all"": {} }")

I then parse out the request and see if an optional sorting parameter was passed in. If it was, I create a new SearchDescriptor<MyData>() which performs that requested sort, and I want to add it to my original search criteria. Obviously .Search() will actually perform an HTTP call, so it can't happen as it is today, but how can I stick a series of SearchDescriptor calls together and then perform the search at the end?

1

There are 1 answers

0
bittusarkar On BEST ANSWER

You can build SearchDescriptor incrementally as under. I've used aggregations instead of facets (which are deprecated now) but I hope you get the idea.

var sd = new SearchDescriptor<MyData>();

sd = sd.QueryRaw(<raw query string>);

if (<should sort>)
{
    string fieldToBeSortedOn; // input from user
    bool sortInAscendingOrder; // input from user
    if (sortInAscendingOrder)
    {
        sd = sd.Sort(f => f
            .Ascending()
            .OnField(fieldToBeSortedOn));
    }
    else
    {
        sd = sd.Sort(f => f
            .Descending()
            .OnField(fieldToBeSortedOn));
    }
}

if (<should compute aggregations>)
{
    sd = sd.Aggregations(a => a
        .Terms(
            "term_aggs", 
            t => t
                .Field(<name of field to compute terms aggregation on>)));
}

var search = esClient.Search<MyData>(s => sd);