I'm trying to learn Elastic Search
with help of php composer package. I'm having a index
with the name of media_data
which contains nits_account
, nits_url
, session_id
, timestamp
fields. I want to have filters based on above fields and it should be in and
operator. my current query code is:
$items = $this->elasticsearch->search([
'index' => $index_name,
'body' => [
'query' => [
'filtered' => [
'filter' => [
'and' => [
['match' => ['nits_account' => 'xyzABCD2190-aldsj']], //API Key
['match' => ['nits_url' => 'google.com']],
]
]
]
]
]
]);
My question:
I'm unable to fetch data. But if I do below code:
$items = $this->elasticsearch->search([
'index' => $index_name,
'body' => [
'query' => [
'bool' => [
'should' => [
['match' => ['nits_account' => $account] ],
['match' => ['nits_url' => $domain] ],
],
],
]
]
]);
I get values in or
operators, but need to have and
operation in it.
nits_account
field to be exact match, I want to have nits_url
with like/wildcard operations, timestamp should be comparable (greater than/less than/between two dates).Try this:
$items = $this->elasticsearch->search([
'index' => $index_name,
'body' => [
'query' => [
'bool' => [
'must' => [
['match' => ['nits_account' => $account] ],
['match' => ['nits_url' => $domain] ]
],
],
]
]
]);
You should use must
keyword, not should
keyword. must
acts like AND operation while should
acts like OR operation.
See this https://stackoverflow.com/a/28768600/5430055
if you need to use conditional match use something like this:
"query": {
"bool": {
"must": [
{
"range": {
"nits_url": {
"gte": 1000,
"lte": 10000
}
}
},
{
"match": {
"nits_account": "$account"
}
}
]
}
}