使用multi_match定义2个筛选器时,弹性查询格式不正确



我很难将一个multi_match查询与两个过滤器组合在一起。

我使用的是Elastic 7.17,并使用PHP指定查询。

错误如下:

{
"error": {
"root_cause": [{
"type": "parsing_exception",
"reason": "[term] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
"line": 1,
"col": 170
}],
"type": "x_content_parse_exception",
"reason": "[1:170] [bool] failed to parse field [filter]",
"caused_by": {
"type": "parsing_exception",
"reason": "[term] malformed query, expected [END_OBJECT] but found [FIELD_NAME]",
"line": 1,
"col": 170
}
},
"status": 400
}

解析器可以单独使用每个过滤器,如果我注释掉其中一个,另一个也可以,但一旦我取消注释两个过滤器,就会出现错误。

这大概表明问题出在我定义多个过滤器的方式上?

然而,我构建的查询与官方的Elastic示例几乎完全相同。

https://www.elastic.co/guide/en/elasticsearch/reference/7.17/query-filter-context.html

我的查询在这里:

'query' => [
'bool' => [
'must' => [
'multi_match' => [
'query' => $keywords,
'fields' => [
'title^4',
'subtitle^4',
]
],
],
'filter' => [
'term' => [
'status' => 'live'
],
'range' => [
'published_date' => [
'lte' => '2022-11-01'
]
]
]
]
]

失败的原因是我将过滤器表示为PHP数组的方式。为了将其转换为JSON数组,PHP需要数组中的数组。

添加额外的方括号会将其变成一个过滤器数组。

'query' => [
'bool' => [
'must' => [
'multi_match' => [
'query' => $keywords,
'fields' => [
'title^4',
'subtitle^4',
]
],
],
'filter' => [
[
'term' => [
'status' => 'live',
],
],
[
'range' => [
'published_date' => [
'lte' => '2022-11-01'
]
]
]
]
]
]
]
];

在JSON编码期间使用JSON_PRETTY_PRINT常量有助于调试。

$json = json_encode($query, JSON_PRETTY_PRINT);