2

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:

  1. 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.

  1. How can I have different search operations with respective fields, I mean I want to have 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).
Nitish Kumar
  • 5,259
  • 12
  • 57
  • 123

1 Answers1

1

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"
          }
        }
      ]
    }
  }
Ishara Madhawa
  • 3,039
  • 4
  • 19
  • 35
  • 1
    Thanks it helped me, I got stuck with minus (-) sign in my strings, I went through lot of docs then I got to know that we have to have analyzers defined to query over special characters. https://stackoverflow.com/questions/44043372/match-string-with-minus-character-in-elasticsearch Hope it helps someone – Nitish Kumar Jan 27 '20 at 10:32