2

I'm using NEST to query ElasticSearch and I'm looking to create a conditional filter. I need the query to match on category AND the optional title and chapter fields. I'm doing an aggregate to get unique values. The problem is that the filter seems to be doing an OR on the filter fields. Any ideas what I'm doing wrong in this example?

FilterContainer filter = new FilterContainer();

filter = Filter<Page>.Term("category", "1575");

if (title != null)
{
    filter &= Filter<Page>.Term("title", title);
}

if (chapter != null)
{
    filter &= Filter<Page>.Term("chapter", chapter);
}

var result = client.Search<Page>(s => s
    .Index(index)
    .Filter(filter)
    .Size(0)
    .Aggregations(a => a
        .Terms("my_agg", st => st
            .Field("title")
        )
    )
);

var myAgg = result.Aggs.Terms("my_agg");
IList<KeyItem> lst = myAgg.Items;
return lst;

1 Answer 1

4

This will give you results over all rows as your filters will not be used at all for aggregations. Hence it appears that the filter is doing an OR operation. For your requirements, you need to use filter aggregations in which the filter is specified inside the aggregation. Have a look at http://www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-aggregations-bucket-filter-aggregation.html for more information.

For your purpose, below is the updated code for creating the search request and processing the response.

var result = client.Search<Page>(s => s
    .Index(index)
    .Size(0)
    .Aggregations(fa => fa
        .Filter("filtered_aggs", f => f
            .Filter(fd => filter)
                .Aggregations(ta => ta
                    .Terms("my_agg", st => st
                        .Field("title")
                    )
                )
            )
        )
    )
);

var myAgg = result.Aggs.Nested("filtered_aggs").Terms("my_agg");
IList<KeyItem> lst = myAgg.Items;
return lst;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.