user1187968
user1187968

Reputation: 7986

Elasticsearch search query: nested query with OR-gates & AND-gates

I have docs as follow: { "name": "...", "country": "...", }

I need to find. either one of the following criteria:

How should be write this nested query?

Upvotes: 0

Views: 91

Answers (1)

lkatiforis
lkatiforis

Reputation: 6255

Assuming the default fields mapping is defined, you can use boolean queries as follows:

{
    "query": {
        "bool": {
            "should": [
                {
                    "bool": {
                        "filter": [
                            {
                                "term": {
                                    "name.keyword": "John"
                                }
                            },
                            {
                                "term": {
                                    "country.keyword": "US"
                                }
                            }
                        ]
                    }
                },
                {
                    "bool": {
                        "filter": [
                            {
                                "term": {
                                    "name.keyword": "Andy"
                                }
                            },
                            {
                                "term": {
                                    "country.keyword": "UK"
                                }
                            }
                        ]
                    }
                }
            ]
        }
    }
}

You should use must instead of filter if you want the query to contribute to the score.

must

The clause (query) must appear in matching documents and will contribute to the score.

filter

The clause (query) must appear in matching documents. However unlike must the score of the query will be ignored. Filter clauses are executed in filter context, meaning that scoring is ignored and clauses are considered for caching.

Upvotes: 2

Related Questions