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令牌
相关推荐
曲幽1 小时前
我用了FastApiAdmin后,连夜把踩过的坑都整理出来了
redis·python·postgresql·vue3·fastapi·web·sqlalchemy·admin·fastapiadmin
前端若水3 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
涛声依旧-底层原理研究所4 小时前
残差连接与层归一化通俗易懂的详解
人工智能·python·神经网络·transformer
csdn_aspnet4 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
fantasy_arch4 小时前
pytorch人脸匹配模型
人工智能·pytorch·python
熊猫_豆豆4 小时前
广义相对论水星近日点进动完整详细数学推导
python·天体·广义相对论
web3.08889994 小时前
1688 图搜接口(item_search_img / 拍立淘) 接入方法
开发语言·python
AI算法沐枫5 小时前
深度学习python代码处理科研测序数据
数据结构·人工智能·python·深度学习·决策树·机器学习·线性回归
X1A0RAN6 小时前
解决Pycharm中部分文件或文件夹被隐藏不展示问题
ide·python·pycharm
MomentYY6 小时前
第 3 篇:让 Agent 学会分工,LangGraph 构建多 Agent系统
人工智能·python·agent