在弹性搜索中进行术语查询

时间:2018-06-18 13:07:52

标签: php codeigniter elasticsearch search

我需要在弹性搜索中搜索多个ID。与SQL中的IN相同。 当我编写静态多个ID时,它可以工作,但是当我创建ID数组然后内爆为ES创建逗号分隔的ID。它不起作用。

内爆查询:

$ids = array();
foreach ($this->session->userdata('cart') as $key => $value) {
 $ids[] = trim($key);
}


$params = [

            'index' => ES_INDEX_PD,
            'body' => [
                'query' => [
                    'constant_score' => [
                        'filter' => [
                            'terms' => [ 
                                'id' => [implode(",", $ids)]
                            ]
                        ],
                    ]

                ]
            ]
        ];

        $products = $this->elasticsearch->client->search($params);

这是来自爆炸的结果......不起作用

Array ( [index] => example-prod [body] => Array ( [query] => Array ( [constant_score] => Array ( [filter] => Array ( [terms] => Array ( [id] => Array ( [0] => 10241308,10928958 ) ) ) ) ) ) ) 

这是传递给查询的静态ID。这工作

Array ( [index] => example-prod [body] => Array ( [query] => Array ( [constant_score] => Array ( [filter] => Array ( [terms] => Array ( [id] => Array ( [0] => 10241308 [1] => 10928958 ) ) ) ) ) ) ) 

1 个答案:

答案 0 :(得分:1)

当您传递 ID 时,无需在implode()处使用额外的,。几个月前我遇到了同样的问题。只需将这样的ID数组传递给terms查询,它就能完美运行。

$ids = array();
foreach ($this->session->userdata('cart') as $key => $value) {
 $ids[] = trim($key);
}

$params = [

            'index' => ES_INDEX_PD,
            'body' => [
                'query' => [
                    'constant_score' => [
                        'filter' => [
                            'terms' => [ 
                                'id' => $ids
                            ]
                        ],
                    ]
                ]
            ]
        ];

$products = $this->elasticsearch->client->search($params);