Elasticsearch指定类型索引请求已弃用,需使用哪种无类型端点?
问题原因
该警告由Elasticsearch版本迭代的接口变更触发:
Elasticsearch 7.x版本开始正式废弃文档类型(Type)概念,8.x版本已完全移除类型相关的接口要求,旧版接口中的
doc_type参数已被弃用,官方要求使用无类型端点完成文档写入。
修复方案
直接删除es.index方法中的doc_type参数即可消除警告,修改后的对应代码行如下:
es.index(index='myIndex', ignore=400, id=i, document=json.loads(docket_content))
额外提示:Elasticsearch索引名要求全小写,建议把原代码中的
myIndex改为myindex,避免后续出现索引命名相关的报错。
优化后的完整代码
以下版本新增了上下文管理器自动释放文件句柄、异常捕获逻辑,稳定性更高:
import requests, json, os from elasticsearch import Elasticsearch # 存放爬取JSON数据的目录 directory = '../spider/' # 连接本地Elasticsearch实例 res = requests.get('http://localhost:9200') print(res.content) es = Elasticsearch([{'host': 'localhost', 'port': '9200'}]) # 文档ID计数器 doc_id = 1 # 遍历目录下所有JSON文件 for filename in os.listdir(directory): if filename.endswith(".json"): fullpath = os.path.join(directory, filename) # 使用with上下文管理器自动关闭文件,避免文件句柄泄漏 with open(fullpath, 'r', encoding='utf-8') as f: try: docket_content = json.load(f) # 写入ES,已移除废弃的doc_type参数 es.index(index='myindex', ignore=400, id=doc_id, document=docket_content) doc_id += 1 except json.JSONDecodeError: print(f"文件{filename}JSON格式错误,已跳过") except Exception as e: print(f"写入文件{filename}失败,错误信息:{str(e)}")
内容的提问来源于stack exchange,提问作者glitchy_itchy
相关产品推荐
相关产品推荐

