Search code examples
elasticsearchelasticsearch-railschewy-gemelasticsearch-ruby

Filtering Elastic search result with must and match giving unexpected result


{
  "body": {
    "query": {
      "bool": {
        "must": {
          "match": {
            "_id": "24"
          }
        },
        "should": [
          {
            "term": {
              "draft_id": "draft_11"
            }
          },
          {
            "term": {
              "draft_id": "non_draft"
            }
          }
        ]
      }
    }
  }
}

result contains below information

{
  "_id": "24",
  "name": "xyz",
  "draft_id": "draft_312"
}

Requirement

I wan to filter record based on:

  • id must match
  • And draft_id should be either non_draft or draft_11

OR in simple words

id = 24 AND (draft_id = "non_draft" OR draft_id = "draft_11")

And if you see the result, it only matches id, but not draft_id field.


Solution

  • You need to move your should clause inside must_clause. Only clauses in must get "AND" among themselves

    {
      "query": {
        "bool": {
          "must": [
            {
              "match": {
                "_id": "24"
              }
            },
            {
              "bool": {
                "should": [
                  {
                    "term": {
                  "draft_id": "draft_11"
                }
                  },
                  {
                 "term": {
                  "draft_id": "draft_11"
                }   
                  }
                ]
              }
            },
            {
              "query_string": {
                "default_field": "FIELD",
                "query": "this AND that OR thus"
              }
            }
          ]
        }
      }
    }