Phil
Phil

Reputation: 335

Should as filter context (OR without scoring in Elasticsarch possible?)

I am trying to setup most efficient way to build an OR without having a scoring, since I want to order my results by business values afterwards.

Unfortunately i don't get it done. :(

What I need:

COLOR=X AND ( title = Y OR description = Z)

What I tried (but it is malformed):

{
"query": {
    "bool": {
        "filter": [
            {
                "term": {
                    "colors.source_name": "braun"
                }
            },
            {
                "should": [
                    {
                        "term": {
                            "title": "sofa"
                        }
                    },
                    {
                        "term": {
                            "description": "sofa"
                        }
                    }
                ]
            }
        ]
    }
}

What I also tried, but it also provided results without "gartenlounge", and especially with scoring:

{
"query": {
    "bool": {
        "filter": [
            {
                "term": {
                    "colors.source_name": "braun"
                }
            }
        ],
        "should": [
            {
                "term": {
                    "title": "sofa"
                }
            },
            {
                "term": {
                    "description": "sofa"
                }
            }
        ]
    }
}

Upvotes: 1

Views: 35

Answers (1)

Benjamin Trent
Benjamin Trent

Reputation: 7566

The following query should work for you:

{
  "query": {
    "bool": {
      "filter": [
        {"term": {
          "colors.source_name": "braun"
        }},
        {"bool": {
          "should": [
            {"term": {"title": "sofa"}},
            {"term": {"description": "sofa"}}
            ]
        }}
      ]
    }
  }
}

You can nest a bool query inside the filter context, and should is only valid from within a bool clause.

It's an old reference sir, but it still checks out:

https://www.elastic.co/guide/en/elasticsearch/guide/current/combining-filters.html

Upvotes: 4

Related Questions