ElasticSearch and searching on multiple fields in PHP

穿精又带淫゛_ 提交于 2019-12-12 13:23:41

问题


I am using the latest version of elasticsearch-php as well as the latest version of MongoDB and ElasticSearch.

I need to do a search on multiple fields that can contain one or multiple values. Example:

country_code should be either NL, BE or DE AND category should contain be AA01, BB01, CC02 or ZZ11

I thought I would solve it as followed (PHP):

$countries = array(“NL”, “BE”, “DE”);
$category = array(“AA01”, “BB01”, “CC02”, “ZZ11”);

$searchParams['body']['query']['bool']['must']['terms']['country'] = $countries;
$searchParams['body']['query']['bool']['must']['terms']['categories'] = $category;
$searchParams['body']['query']['bool']['must']['terms']['minimum_should_match'] = 1;

But the result does not even come close the the data that I expect to get back.

Sometimes $countries and/or $category can only have one element.


回答1:


It is becaue of how PHP arrays work, you are overwriting the terms query each time, instead try something along the lines of:

array(
    'body' => array('query' => 
    'bool' => array(
        'must' => array(
            array('terms' => array('country' => implode(' ', $countries))),
            array('terms' => array('category' => implode(' ', $category))),
        )
    )
))

minimum_should_match is useless with must clause of the query.



来源:https://stackoverflow.com/questions/20818516/elasticsearch-and-searching-on-multiple-fields-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!