ElasticSearch添加status查询条件报400错误求助
问题排查与解决
错误原因
你的查询结构不符合Elasticsearch的DSL规范:bool查询的must字段需要是查询对象的数组,但你当前的写法把multi_match和嵌套的bool直接作为了must数组的键值对(相当于一个关联数组),导致Elasticsearch解析失败,触发parsing_exception。
修正后的代码
把multi_match和status的term查询都作为must数组的独立元素,不需要额外嵌套一层bool(当前需求下完全没必要):
$products = $this->elasticsearch->search([ 'index' => $product->getSearchIndex(), 'type' => $product->getSearchType(), 'body' => [ '_source' => ['category_id', 'title', 'status'], 'size' => 30, 'query' => [ 'bool' => [ 'must' => [ // 第一个查询条件:multi_match [ 'multi_match' => [ 'fields' => ['title^1'], 'type' => 'phrase_prefix', 'query' => $query, ] ], // 第二个查询条件:status的term查询 [ 'term' => ['status' => ProductStatus::ACTIVE] ] ], ], ], ], ]);
优化建议
如果只是过滤status: active,更推荐用filter而非must——filter不会参与评分,性能更优:
'bool' => [ 'must' => [ [ 'multi_match' => [ 'fields' => ['title^1'], 'type' => 'phrase_prefix', 'query' => $query, ] ] ], 'filter' => [ [ 'term' => ['status' => ProductStatus::ACTIVE] ] ] ]
内容的提问来源于stack exchange,提问作者e-goat
相关产品推荐
相关产品推荐

