Search code examples
c#elasticsearchfilteringnest

ElasticSearch (NEST) Query to exclude specific term results


I'm trying to find a QueryContainer query that I can perform on an ElasticSearch result that will essentially filter out any "A" status Items in my resultset. My ProductIndex document contains a field named "StatusCode", and I don't want to return these "A" status' to my search resultsets... I'm having the hardest time finding a way to remove these items.

This query properly finds these "A" status':

.Match(qm => qm
             .Field(f => f.StatusCode)
            .Query("A"));

But I want to do the opposite (not get all the "A" status items, but exclude them)

Based upon other threads I read on here, I came up with the following query, but it's not filtering out these results:

.Bool(b => b
        .MustNot(mn => mn
            .Terms(t => t
                .Field(f => f.StatusCode)
                .Terms("A")
            )
        ));

and

.Bool(b => b
        .MustNot(mn => mn
            .Term(t => t
                .Field(f => f.StatusCode).Value("A")
            )
        ));

But neither removes results that have an "A" statuscode

Kibana value of a result that is still being returned, but has the status "A" code:

enter image description here


Solution

  • The MustNot filter continues to not work for me - I ended up resolving this by performing two search queryies - one based upon the result set obtained from from the first query

    .Match(qm => qm
                 .Field(f => f.StatusCode)
                .Query("A"));
    

    This properly filtered the items to only return the ones I was trying to remove from my primary query. I obtained this document list, then applied this list as an exclusion filter to my underlying request, thus filtering out the items I no longer wanted to return.

    Not as elegant as I would like, but got the job done.