Search code examples
c#elasticsearchnest

ElasticSearch NEST OR query


i've been having some trouble regarding creating a query that searches through different fields. I got the answers i wanted by creating several queries - but for the sake of performance - i want to do this in just one query, if possible.

I've tried setting the query up in several .Should clauses, but it seems that it searches for documents that matches every field, which i think is intended. It looks like this;

 .From(0)
             .Sort(sort => sort
             .Field("priority", SortOrder.Descending))
             .Sort(sort => sort
             .Ascending(a => a.ItemNumber.Suffix("keyword")))
             .Sort(sort => sort
             .Descending(SortSpecialField.Score))
             .TrackScores(true)
             .Size(25)
             .Query(qe => qe
             .Bool(b => b
                .Should(m => m
                   .Match(ma => ma
                      .Boost(1.1)
                      .Field("itemnumber")
                      .Query(ItemNumber)
                     ))
                 .Should(m => m
                    .Match(ma => ma
                        .Boost(1.1)
                        .Field("itemnumber2")
                        .Query(ItemNumber)))
                 .Should(m => m
                    .Match(ma => ma
                        .Boost(1.1)
                        .Field("ean")
                        .Query(ItemNumber)))
                 .Should(m => m
                    .Match(ma => ma
                        .Boost(1.1)
                        .Field("itemalias")
                        .Query(ItemNumber)))
                        )));

What i want it to do is; Search through the Itemnumber and see if a document matches, if not, search through the Itemnumber2 and so on. Is there an efficient way to do this in just one query?


Solution

  • I believe the syntax for a should query with multiple parts should be an array of queries. Your way you would just add multiple separate should queries. What you want should probably look like this:

    .Bool(b => b
        .Should(
            m => m
            .Match(ma => ma
                .Boost(1.1)
                .Field("itemnumber")
                .Query(ItemNumber)),
            m => m
            .Match(ma => ma
                .Boost(1.1)
                .Field("itemnumber2")
                .Query(ItemNumber)),
                m => m
            .Match(ma => ma
                .Boost(1.1)
                .Field("ean")
                .Query(ItemNumber)),
                m => m
            .Match(ma => ma
                .Boost(1.1)
                .Field("itemalias")
                .Query(ItemNumber)))
    

    More here