Search code examples
elasticsearchelasticsearch-dsl

Elasticsearch Query DSL with logical OR and AND conditions


I have the following documents in the Elasticsearch.

{
"id": "1234",
"color": "red"
}

{
"id": "1234",
"color": "burgundy"
}

{ "id": "4321",
  "color": "red"
}

{ "id": "1111",
  "color": "red"
}

{ "id": "2222",
   "color": "red"
}

{ "id": "3333",
   "color": "red"
}

{ "id": "4444",
   "color": "red"
}

{ "id": "5555",
  "color": "red"
}

{ "id": "6666",
  "color": "red"
}

I want to retrieve only those documents that match the following conditions.

  • Documents id with value either 1234 or 4321
  • and Documents with color as red.

I am trying to prepare a query DSL that will return only 2 documents (first one and third one). I have tried the following but it is returning all the documents that have color as red and it is ignoring the first condition.

{"query": 
    {"bool": 
        {"should": [
            {"term": {"id": "1234"}},
            {"term": {"id": "4321"}}
        ],      
        "filter": [
          {"term": {"color": "red"}}
        ]
        }
    }
}

Can someone help with this? Thanks in advance.


Solution

  • {
        "query": {
            "bool": {
                "must": [
                    {
                        "terms": {
                            "id": [
                                "1234",
                                "4321"
                            ]
                        }
                    },
                    {
                        "term": {
                            "color": "red"
                        }
                    }
                ]
            }
        }
    }