ElasticSearch Filter Multiple Fields Required

287 Views Asked by At

I have this query (via PHP client) for ElasticSearch 6.2:

[
    "query"=> [
        "bool" => [
            "filter" => [
                "term" => [ "row.name" => $name ],
                "term" => [ "row.origin" => $origin ]
            ]
        ]
    ],
    "size" => "10"
]

It works if I use just one search for either row.name or row.origin, but with both it works like an OR and returns all results. How can I filter to only return documents that are an exact match for row.name AND row.origin

1

There are 1 best solutions below

0
On BEST ANSWER

You took the right way, but I'm guessing that you missed parenthesis.

Instead of:

[
    "query"=> [
        "bool" => [
            "filter" => [
                "term" => [ "row.name" => $name ],
                "term" => [ "row.origin" => $origin ]
            ]
        ]
    ],
    "size" => "10"
]

You should have:

[
    "query"=> [
        "bool" => [
            "filter" => [
                ["term" => [ "row.name" => $name ]],
                ["term" => [ "row.origin" => $origin ]]
            ]
        ]
    ],
    "size" => "10"
]

In your case you created a map with two same (term) keys:

[
  "term" => [ "row.name" => $name ],
  "term" => [ "row.origin" => $origin ]
]

So the second term overrode the first one and in reality, you sent:

[
  "term" => [ "row.origin" => $origin ]
]

To send multiple term filters you need so they will be treated as a list:

[
  ["term" => [ "row.name" => $name ]],
  ["term" => [ "row.origin" => $origin ]]
]