Elasticsearch function_score查询格式错误排查求助
Elasticsearch function_score 查询解析错误修复
错误信息
"type":"parsing_exception", "reason":"[function_score] malformed query, expected [END_OBJECT] but found [FIELD_NAME]"
问题描述
原本有一段可正常运行的PHP Elasticsearch查询代码,想要添加function_score功能,基于tstamp字段给近期内容提升权重。添加代码后出现上述解析错误。
错误的完整查询代码
'query' => [ 'function_score' => [ 'functions' => [ [ 'filter'=> [ 'range' => [ 'tstamp' => [ 'gte' => 'now-1y', 'lte' => 'now' ] ] ], 'weight' => 5 ], [ 'filter' => [ 'range' => [ 'tstamp' => [ 'gte' => 'now-3yr', 'lte' => 'now-1yr' ] ] ], 'weight' => 2 ] ], 'boost_mode' => 'multiply' ], 'bool' => [ 'filter' => [ ['range' => [ 'starttime' => ['lte' => $now], ]] ], 'must' => [ ["multi_match" => [ 'fuzziness' => 'auto', 'query' => $_REQUEST['kw'], 'fields' => [ 'content^2', 'teaser^2', 'bodytext^2', 'title^5', 'header^3' ], ]], ['bool' => [ 'should' => [ ['match' => ['sys_language_uid' => $sysLanguageUid]], ['match' => ['sys_language_uid' => -1]], ], 'minimum_should_match' => 1, ]], ], 'must_not' => [ ['match' => ['hidden' => 1]], ['match' => ['deleted' => 1]], ['match' => ['no_search' => 1]] ], ] ],
问题原因
Elasticsearch的query节点下只能有一个顶级查询类型,不能同时并列function_score和bool两个字段。你现在把两个查询类型平级放在query里,导致解析器无法识别,抛出语法错误。
正确的做法是把原来的bool查询作为function_score的query参数,让function_score基于这个bool查询的结果来应用权重函数。
修复后的代码
'query' => [ 'function_score' => [ // 把原有的bool查询放到function_score的query字段里 'query' => [ 'bool' => [ 'filter' => [ ['range' => [ 'starttime' => ['lte' => $now], ]] ], 'must' => [ ["multi_match" => [ 'fuzziness' => 'auto', 'query' => $_REQUEST['kw'], 'fields' => [ 'content^2', 'teaser^2', 'bodytext^2', 'title^5', 'header^3' ], ]], ['bool' => [ 'should' => [ ['match' => ['sys_language_uid' => $sysLanguageUid]], ['match' => ['sys_language_uid' => -1]], ], 'minimum_should_match' => 1, ]], ], 'must_not' => [ ['match' => ['hidden' => 1]], ['match' => ['deleted' => 1]], ['match' => ['no_search' => 1]] ], ] ], 'functions' => [ [ 'filter'=> [ 'range' => [ 'tstamp' => [ 'gte' => 'now-1y', 'lte' => 'now' ] ] ], 'weight' => 5 ], [ 'filter' => [ 'range' => [ 'tstamp' => [ 'gte' => 'now-3yr', 'lte' => 'now-1yr' ] ] ], 'weight' => 2 ] ], 'boost_mode' => 'multiply' ] ],
说明
修复后,function_score会先执行内部的bool查询获取匹配结果,再对这些结果应用你定义的权重函数,根据tstamp的时间范围提升对应文档的权重,同时保持原有的查询逻辑不变。
内容的提问来源于stack exchange,提问作者user20291865
相关产品推荐
相关产品推荐

