Elasticsearch使用Nested Filter排序提示categories路径下对象非nested类型
错误原因及解决办法
错误产生原因
该报错的核心原因是Elasticsearch 索引中categories字段的映射(Mapping)类型不匹配:
- Elasticsearch 默认将对象数组字段的类型设为普通
object类型,会把数组内所有对象的同名字段打平合并存储,丢失单个对象内不同字段的关联关系 - 你编写的排序规则中使用了
nested_path、nested_filter这类仅nested类型字段支持的参数,当字段未提前声明为nested类型时,就会触发该异常。
解决步骤
- 调整索引映射,将
categories字段声明为nested类型
如果是创建新索引,可直接使用如下映射定义:
PUT /你的商品索引名称 { "mappings": { "properties": { "title": { "type": "text" }, "categories": { "type": "nested", "properties": { "title": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "pivot": { "properties": { "priority": { "type": "integer" } } } } } } } }
如果是已有线上索引无法直接删除重建,可先新增一个nested类型的分类字段,再通过_reindex接口将旧数据迁移到新字段,或直接重建索引后重新导入全量商品数据。
2. 数据导入完成后,你原有的排序规则即可正常运行,完整的筛选+排序查询参考如下:
GET /你的商品索引名称/_search { "query": { "nested": { "path": "categories", "query": { "term": { "categories.title.keyword": "Category 1" } } } }, "sort": [ { "categories.pivot.priority": { "order": "asc", "nested_path": "categories", "nested_filter": { "term": { "categories.title.keyword": "Category 1" } } } } ] }
执行后会返回所有关联了Category 1的商品,且按该分类对应的pivot.priority值升序排列。
内容的提问来源于stack exchange,提问作者TCS
相关产品推荐
相关产品推荐

