You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:15:03