Kiran
Kiran

Reputation: 3

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.

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.

Upvotes: 0

Views: 1575

Answers (1)

Johnny
Johnny

Reputation: 694

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

Upvotes: 2

Related Questions