OpenSearch添加keyword子字段失败,字段类型变更报错求助
解决OpenSearch字段类型修改错误:metadata.cloudAccountId无法从text改为ObjectMapper
问题
创建OpenSearch索引时,尝试为metadata.cloudAccountId字段配置text类型及keyword子字段以支持排序,触发报错,提示该字段无法从text类型修改为ObjectMapper。
错误信息
{"timestamp": "2023-02-26T16:06:23.388759Z", "level": "INFO", "name": "denali_syncer.opensearch", "message": "create index cd.io.schema.asset mapping, status 400, body: b'{\"error\":{\"root_cause\":[{\"type\":\"mapper_parsing_exception\",\"reason\":\"Failed to parse mapping [_doc]: mapper [metadata.cloudAccountId] cannot be changed from type [text] to [ObjectMapper]\"}],\"type\":\"mapper_parsing_exception\",\"reason\":\"Failed to parse mapping [_doc]: mapper [metadata.cloudAccountId] cannot be changed from type [text] to [ObjectMapper]\",\"caused_by\":{\"type\":\"illegal_argument_exception\",\"reason\":\"mapper [metadata.cloudAccountId] cannot be changed from type [text] to [ObjectMapper]}},\"status\":400}'"}
现有错误映射
{ "cloudAccountId" : {"type" : "text"}, "cloudAccountId.keyword" : {"type" : "keyword"}, }
相关代码
url = f'{OPENSEARCH_URL}/{dataset}' response = requests.post(url=url, headers=HEADERS, data=fields_json)
原因分析
- 映射格式错误:直接定义
cloudAccountId.keyword字段会被OpenSearch识别为独立嵌套字段,而非cloudAccountId的子字段,与已存在的metadata.cloudAccountId(text类型)产生类型冲突。 - 请求方式错误:POST请求到索引路径默认是创建文档,而非创建/更新索引映射,正确的索引创建需使用PUT请求。
解决方案
1. 修正映射格式
正确的text+keyword子字段需通过fields属性定义,而非直接拼接字段名:
{ "mappings": { "properties": { "metadata": { "properties": { "cloudAccountId": { "type": "text", "fields": { "keyword": { "type": "keyword" } } } } } } } }
2. 处理已有索引
- 无数据场景:直接删除现有索引,使用修正后的映射重新创建。
- 有数据场景:
- 创建新索引并应用正确映射。
- 使用OpenSearch的
_reindexAPI将旧索引数据迁移到新索引。 - 删除旧索引,将新索引重命名为原索引名。
3. 修正代码请求方式
创建索引需使用PUT请求,示例代码:
import requests import json # 修正后的映射数据 correct_mapping = { "mappings": { "properties": { "metadata": { "properties": { "cloudAccountId": { "type": "text", "fields": { "keyword": { "type": "keyword" } } } } } } } } url = f'{OPENSEARCH_URL}/{dataset}' # 使用PUT请求创建索引并设置映射 response = requests.put(url=url, headers=HEADERS, data=json.dumps(correct_mapping))
内容的提问来源于stack exchange,提问作者soubhagya
相关产品推荐
相关产品推荐

