ElasticSearch配置integer等数值类型Mapping不生效问题咨询
问题根因
- 1、
helpers.bulk批量导入时未指定和映射匹配的doc_type参数:你给activity_body类型配置了自定义映射,但ES默认导入时使用的文档类型是_doc,完全没有匹配到你配置的映射规则,ES自动根据CSV读取的字符串内容给_doc类型的所有字段设置了text类型。 - 2、如果你的ES版本是7.x及以上,已经默认废弃了文档类型(doc_type),保留
include_type_name和自定义doc_type的写法本身就不符合版本规范,更容易出现类型不匹配问题。 - 3、从CSV中读取的所有值默认都是字符串类型,即使映射配置正确,也建议手动做一次类型转换,避免部分特殊格式内容触发ES自动类型推导失败。
- 4、先创建空索引再单独更新映射的操作,存在中间间隔期误写入触发自动建映射的风险,更推荐创建索引时直接附带mapping配置。
修正方案
适配ES7.x及以上版本(推荐)
ES7+已经移除了doc_type,直接调整映射写法和导入逻辑即可:
# 创建索引时直接指定mapping,无需单独调用put_mapping mapping = { "mappings": { "properties": { "ActivitatID": {"type": "long"}, "Assignaturas": {"type": "text"}, "Competencias": {"type": "text"}, "Descripcion": {"type": "text"}, "EdadMaxima": {"type": "integer"}, "EdadMinima": {"type": "integer"}, "Guardados": {"type": "integer"}, "Idioma": {"type": "text"}, "Link": {"type": "text"}, "Nombre": {"type": "text"}, "Puntuacion": {"type": "double"}, "Tags": { "type": "text"}, "Votos": {"type": "integer"}, "Tipo": {"type": "text"} } } } # 先删除已存在的错误索引(如果需要) if es.indices.exists(index='activities'): es.indices.delete(index='activities') # 创建索引附带mapping es.indices.create(index='activities', body=mapping) # 导入数据时增加类型转换 def transform_row(row): # 数值字段手动转类型,避免字符串导入问题 row['ActivitatID'] = int(row['ActivitatID']) if row['ActivitatID'] else None row['EdadMaxima'] = int(row['EdadMaxima']) if row['EdadMaxima'] else None row['EdadMinima'] = int(row['EdadMinima']) if row['EdadMinima'] else None row['Guardados'] = int(row['Guardados']) if row['Guardados'] else None row['Puntuacion'] = float(row['Puntuacion']) if row['Puntuacion'] else None row['Votos'] = int(row['Votos']) if row['Votos'] else None return row with open(file_path) as f: reader = csv.DictReader(f) # 转换每行数据后再批量导入 processed_rows = [transform_row(row) for row in reader] helpers.bulk(es, processed_rows, index="activities")
适配ES6.x及更早版本(保留自定义doc_type)
如果你的ES版本支持doc_type,只需要在bulk时指定对应的doc_type即可:
# 原有put_mapping逻辑不变,导入时增加doc_type参数 with open(file_path) as f: reader = csv.DictReader(f) processed_rows = [transform_row(row) for row in reader] # 同样建议加类型转换 helpers.bulk(es, processed_rows, index="activities", doc_type="activity_body")
内容的提问来源于stack exchange,提问作者Laura Galera
相关产品推荐
相关产品推荐

