1
votes

I'm new to ElasticSearch and I'm using NEST to run my queries. I need to be able to add X amount of filtering terms to my query.

For now my query looks like this:

var page = new Page
{
    Id = 1,
    Name = "JR-11 Hyper black"
};

var tags = new Dictionary<string, string[]>
{
    { "Size", new[] { "16", "17", "18" }},
    { "Color", new[] { "Bronze", "Hyper Black", "Flat Black" }}
};

page.Tags = tags;

ElasticClient.Index(page, idx => idx.Index("pages"));

var result = ElasticClient.Search<Page>(
    body => body.Query(query => query.ConstantScore(
        csq => csq.Filter(filter => filter.Term("tags.Size", "17" ))))
    .Take(1000));

var pages = result.Documents.ToList();

The problem I have is with the csq.Filter(filer => filter.Term("tags.Storlek")

I need to be able to add a dynamic amount of such filters. Can't really find anything in the documentation for the 2.3 version that I'm using.

2

2 Answers

0
votes

Fluent API should allow for something like this:

string[] filterTerms = { ... };

var result = ElasticClient.Search<Page>(
    body => body.Query(query => query.ConstantScore(
    csq =>
    {
        var combinedFilters = csq.Filter(filter => filter.Term("tags.Size", "17" ));

        // add an additional, dynamic amount of filters
        foreach (string filterTerm in filterTerms)
            combinedFilters = combinedFilters.Filter(filter => filter.Term(filterTerm, ...));

        return combinedFilters;
    }))
    .Take(1000));
0
votes

I ended up with this, seems to work as needed :)

 var result = ElasticClient.Search<Page>(
            body => body.Query(query => query.ConstantScore(csq => csq.Filter(f =>
            {
                var ff = f.Term("tags.Size", "17");

                // This will be replaced with a loop containing filter terms
                ff &= f.Term("tags.Size", "16");
                ff &= f.Term("tags.Size", "19");

                return ff;
            }))).Take(1000));

Thanks for your answer that got me in the right direction Thomas :)