创建带Percolator支持的Elasticsearch动态映射模板及字段映射疑问
Elasticsearch动态映射模板添加Percolator字段及查询字段映射问题
初始问题
我正在创建如下动态索引映射模板:
PUT my-index-000001 { "mappings": { "dynamic_templates": [ { "strings": { "match_mapping_type": "string", "mapping": { "type": "keyword", "ignore_above": 256 } } } ] } }
想在该模板中添加一个percolator字段,尝试了如下写法但无法生效:
{ "mappings": { "query": { "type": "percolator" }, "dynamic_templates": [ { "strings": { "match_mapping_type": "string", "mapping": { "type": "keyword", "ignore_above": 256 } } } ] } }
请问如何创建支持percolator的动态映射模板?
更新后问题
我创建了如下动态映射,该模板可以正常生效:
PUT my-index-000001 { "mappings": { "properties": { "query": { "type": "percolator" } }, "dynamic_templates": [ { "strings": { "match_mapping_type": "string", "mapping": { "type": "keyword", "ignore_above": 256 } } } ] } }
但导入如下文档时:
PUT /my-index-000001/_doc/1?refresh { "action": { "webhook": { "tenantId": "tenantA" } }, "query": { "query_string": { "query": "message: bonsai" } } }
出现如下错误:
{ "error": { "root_cause": [ { "type": "query_shard_exception", "reason": "No field mapping can be found for the field with name [message]", "index_uuid": "R6UGg60fQW-lPmHPXrhxBQ", "index": "my-index-000001" } ], "type": "document_parsing_exception", "reason": "[11:3] failed to parse: No field mapping can be found for the field with name [message]", "caused_by": { "type": "query_shard_exception", "reason": "No field mapping can be found for the field with name [message]", "index_uuid": "R6UGg60fQW-lPmHPXrhxBQ", "index": "my-index-000001" } }, "status": 400 }
请问是否要求查询字符串中指定的字段必须在映射中实际存在?
解答
1. 正确添加Percolator字段的动态映射模板
你最初的错误写法是直接在mappings下定义query字段,正确的做法是把Percolator字段放在properties中(也就是你更新后的写法)。因为Elasticsearch的字段映射必须声明在properties节点下,直接在mappings下定义字段会被系统忽略,所以之前的写法无法生效。
2. 查询字符串字段的映射要求
是的,当向Percolator字段存入查询时,Elasticsearch会验证查询中涉及的字段是否存在于索引映射中(或能否通过动态映射自动创建)。
你的动态模板设置了所有字符串类型字段默认映射为keyword,但message字段还未被创建,且存入Percolator查询时不会触发动态映射创建该字段——动态映射仅在存入包含该字段的普通文档时才会触发。
有两种解决方法:
- 提前定义
message字段映射:在索引的properties中显式声明message字段的类型,示例:
PUT my-index-000001 { "mappings": { "properties": { "query": { "type": "percolator" }, "message": { "type": "text" // 根据查询需求选择类型,text支持全文检索 } }, "dynamic_templates": [ { "strings": { "match_mapping_type": "string", "mapping": { "type": "keyword", "ignore_above": 256 } } } ] } }
- 关闭字段存在性验证:在Percolator字段的映射中添加
allow_unmapped_fields_in_query_string参数,允许查询字符串引用未定义的字段,示例:
PUT my-index-000001 { "mappings": { "properties": { "query": { "type": "percolator", "allow_unmapped_fields_in_query_string": true } }, "dynamic_templates": [ { "strings": { "match_mapping_type": "string", "mapping": { "type": "keyword", "ignore_above": 256 } } } ] } }
这个参数会让Elasticsearch跳过字段映射检查,后续存入包含message字段的普通文档时,动态映射会自动创建该字段的映射。
内容的提问来源于stack exchange,提问作者user1189332
相关产品推荐
相关产品推荐

