1

I'm using NEST query to filter records from elastic.

The following query will filter records based on phrase and list of sourceIds. But I would like to exclude some documents from the result if their URL contains ideaArticles list.

var result = ElasticSearchClientConnection.Client.Search<T>(s => s
                .Query(q => q.Match(p => p.Field(f => f.Body).Query(phrase))
                            && q.Terms(p => p.Field(f => f.SourceId).Terms(sourceIds))
                            && !q.Terms(p => p.Field(f => f.URL).Terms(ideaArticles))
                ).Take(take));
5
  • 1
    Bool query with must_not clause should help :) Commented May 29, 2018 at 7:37
  • I've tried that, it does not help me. ElasticSearchClientConnection.Client.Search<T>(s => s .Query(q => q.Bool(b => b.MustNot(m => m.Terms(p => p.Field(f => f.URL).Terms(ideaArticles))) ))); Commented May 29, 2018 at 15:32
  • Could you share index mapping? Commented May 29, 2018 at 17:09
  • yes. Client.CreateIndex(this.DefaultIndex, c => c .Settings(s => s .NumberOfShards(numberOfShards) .NumberOfReplicas(numberOfReplicas) .BlocksReadOnly(false) ) .Mappings(m => m .Map<PercolatedQuery>(mm => mm .AutoMap() .Properties(p => p // map the query field as a percolator type .Percolator(pp => pp .Name(n => n.Query)))))); Commented May 29, 2018 at 17:13
  • @Rob Do you know how can I pass a list of string to MatchPhrase? It will work with one phrase but I have a list of phrases ElasticSearchClientConnection.Client.Search<T>(s => s.Query(q => !q.MatchPhrase(p => p.Field(f => f.URL).Query("feeds.mashable.com/~r/Mashable/~3/Y_1a8VwnsEk/")))); Commented May 29, 2018 at 19:41

1 Answer 1

1

I resolved this issue with MatchPhrase. But since I had a list of phrases, I had to create a query on the fly.

var result =
                ElasticSearchClientConnection.Client.Search<T>(s =>
                    s.Query(q => q.Match(p => p.Field(f => f.Body).Query(phrase))
                                 && q.Terms(p => p.Field(f => f.SourceId).Terms(sourceIds))
                                 && BuildMatchPhraseQueryContainer(q, ideaArticles)).Take(take));

and this is the method to create the query on the fly

private QueryContainer BuildMatchPhraseQueryContainer(QueryContainerDescriptor<T> qd, List<string> phrases)
        {
            QueryContainer queryContainer = new QueryContainer();
            foreach (var phrase in phrases)
            {
                queryContainer &= !qd.MatchPhrase(m => m.Field(f => f.URL).Query(phrase));
            }
            return queryContainer;
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.