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令牌
相关推荐
ZH154558913116 小时前
Flutter for OpenHarmony Python学习助手实战:API接口开发的实现
python·学习·flutter
小宋102116 小时前
Java 项目结构 vs Python 项目结构:如何快速搭一个可跑项目
java·开发语言·python
一晌小贪欢17 小时前
Python 爬虫进阶:如何利用反射机制破解常见反爬策略
开发语言·爬虫·python·python爬虫·数据爬虫·爬虫python
躺平大鹅17 小时前
5个实用Python小脚本,新手也能轻松实现(附完整代码)
python
yukai0800817 小时前
【最后203篇系列】039 JWT使用
python
独好紫罗兰17 小时前
对python的再认识-基于数据结构进行-a006-元组-拓展
开发语言·数据结构·python
Dfreedom.17 小时前
图像直方图完全解析:从原理到实战应用
图像处理·python·opencv·直方图·直方图均衡化
铉铉这波能秀18 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
怒放吧德德18 小时前
Python3基础:基础实战巩固,从“会用”到“活用”
后端·python