Python elasticsearch客户端连接常见问题整理

python 访问 elasticsearch

在python语言中,我们一般使用 pip install elasticsearch 软件包,来访问es服务器。

正确用法

本地安装elasticsearch时,应指定与服务端相同的大版本号:

sh 复制代码
pip install elasticsearch==7.17.0

然后就可以正确创建ES客户端对象了。访问es服务端的代码格式,建议如下:

python 复制代码
from elasticsearch import Elasticsearch

es = Elasticsearch("http://username:password@host:port")

# 或者采用如下方式创建,一般用于es集群连接:
es = Elasticsearch(
    [{'host': "192.168.1.1", 'port': 9200, 'scheme': "http"}],
    http_auth=(username, password)
)

print(es.info())
print(es.ping()) # True or False

常见错误

使用 python elasticsearch 连接ES服务器过程,主要问题是客户端与服务端的版本不匹配。

1. 版本不一致

默认情况下,使用 pip install elasticsearch 安装的 es客户端版本是最新的8.17版。而ES服务端的版本是7。

当客户端与服务端的大版本不一致时,将会报错(UnsupportedProductError)。

2.缺少scheme

复制代码
TypeError: NodeConfig.__init__() 缺少 scheme

3.无法识别ES服务端

错误创建的客户端对象,无法访问和识别ES服务端。

客户端创建代码:

python 复制代码
es = Elasticsearch(
    [{'host': "192.168.1.1", 'port': 9200}],
    basic_auth=(username, password)
)

报错信息:

复制代码
ElasticsearchWarning: The client is unable to verify that the server is Elasticsearch due security privileges on the server side

4.http_auth 废弃

elasticsearch v7版本使用 http_auth 创建Elasticsearch客户端对象。而 v8版本废弃了http_auth,改用 basic_auth 或 bearer_auth。因此,当使用v8版本的elasticsearch客户端时,以下代码将报错:

python 复制代码
es = Elasticsearch(
    [{'host': "192.168.1.1", 'port': 9200}],
    http_auth=(username, password)
)

执行代码提示 es中的 http_auth已废弃:

复制代码
es the 'http_auth' parameter is deprecated, use 'basic_auth' or 'bearer_auth' instead

basic_auth 接受一个元组,包含你的用户名和密码,用法与v7的 http_auth相同。

bearer_auth 适用于使用Bearer令牌时(例如通过OAuth2获取的访问令牌)。

复制代码
bearer_auth='your_bearer_token'  # 替换为你的Bearer令牌
相关推荐
风吹心凉19 分钟前
python3基础2026.7.22
开发语言·python
Elasticsearch1 小时前
Elastic 与 Deductive AI 携手合作,加速工程团队的 agent 式事件调查
elasticsearch
小猴子爱上树2 小时前
一站式解决图片视频翻译难题的高效AI工具
人工智能·python·音视频
Elasticsearch2 小时前
将你的 Grafana Kubernetes 仪表板迁移到 Elastic Observability:相同的 PromQL,30 倍更快的查询
elasticsearch
weixin_538601972 小时前
智能体测开Day31
开发语言·python
lbb 小魔仙2 小时前
Git + Python 项目工作流最佳实践:pre-commit、CI、CHANGELOG 自动化
git·python·ci/cd
dyxal2 小时前
最长公共子序列(LCS)
python·算法
你驴我2 小时前
WhatsApp Cloud API 速率限制下的令牌桶与退避策略实践
网络·后端·python
AC赳赳老秦2 小时前
司法公开数据采集应用:OpenClaw 抓取裁判文书公开信息,批量整理同类参考案例
java·大数据·python·数据挖掘·数据分析·php·openclaw
小大宇3 小时前
Python 集成 Conda
开发语言·python·conda