Monday, 6 January 2020

Elasticsearch multi_match in combination with normal match

I have the following function which searches for results in elasticsearch.

I want to do the following request with PHP and Guzzle.

  /**
   * {@inheritdoc}
   */
  public function sendSearchRequest($es_node, $request) {
    try {
      if (isset($es_node)) {
        $ssl = $es_node->get('field_ess_verify_ssl')->value;
        $ssl_val = $ssl ? 'https://' : 'http://';

        $body = [
          'json' => [
            'query' => [
              'bool' => [
                'should' => [
                  [
                    'multi_match' => [
                      'query' => $request->get('search'),
                      'fields' => ['message', 'event.type'],
                      'operator' => 'AND',
                    ],
                  ],
                  [
                    'match' => [
                      'event.type' => $request->get('type'),
                    ],
                  ],
                  [
                    'match' => [
                      'event.labels' => $request->get('label'),
                    ],
                  ],
                ],
              ],
            ],
          ],
        ];

        $response = $this->httpClient->request('POST', $ssl_val . $es_node->get('field_ess_host')->value . ':' . $es_node->get('field_ess_port')->value . '/***/***/_search?pretty', $body)
          ->getBody()
          ->getContents();

        return json_decode($response, TRUE)['hits']['hits'] ?? '';
      }
    } catch (Exception $exception) {
      \Drupal::logger(__METHOD__)->error('No ES node has been found.');
      return FALSE;
    }
  }

But with this i get a parsing exception which means that the multi_match doesn't work this way. If i use a 'normal' match in that place it's working fine but then i am limited to 1 field.

The other match fields uses other form fields for input and that has always one value.

But with form field 'Description search' i want to look in multiple fields with the AND operator.

Anyone knows how to fix this?

Screenshot of the form:

enter image description here



from Elasticsearch multi_match in combination with normal match

No comments:

Post a Comment