使用elasticsearch-py是python操作elasticsearch最官方直接的方式。1. 首先通过pip install elasticsearch安装库;2. 导入elasticsearch类并实例化客户端连接本地或远程实例;3. 使用ping()方法检测连接状态;4. 调用index()、get()、search()、update()、delete()等方法实现增删改查;5. 连接生产环境集群时需配置节点地址列表、启用https并设置ssl_context验证ca证书;6. 启用http_auth=('username', 'password')进行基本认证;7. 设置timeout等参数提升连接稳定性;8. 将证书路径和认证信息妥善保管,避免泄露。整个过程封装良好,api直观易用,能高效完成与elasticsearch的交互。

用Python操作Elasticsearch,最直接也是最官方的途径就是使用
elasticsearch-py
要开始用
elasticsearch-py
pip install elasticsearch
安装好之后,就可以实例化客户端并开始操作了。连接本地的Elasticsearch实例通常非常简单:
立即学习“Python免费学习笔记(深入)”;
from elasticsearch import Elasticsearch
# 默认连接到 localhost:9200
es = Elasticsearch("http://localhost:9200")
# 检查连接是否成功,ping()方法会发送一个HEAD请求
if es.ping():
print("成功连接到Elasticsearch!")
else:
print("无法连接到Elasticsearch,请检查服务是否运行或地址是否正确。")
# 索引一个文档
doc = {
'author': '张三',
'text': 'Python操作Elasticsearch真是太方便了。',
'timestamp': '2023-10-27T10:00:00'
}
resp = es.index(index="my_index", id=1, document=doc)
print(f"索引文档结果: {resp['result']}")
# 获取一个文档
get_resp = es.get(index="my_index", id=1)
print(f"获取文档内容: {get_resp['_source']}")
# 搜索文档
# 最简单的match_all查询,获取所有文档
search_body = {
"query": {
"match_all": {}
}
}
search_resp = es.search(index="my_index", body=search_body)
print(f"搜索到 {search_resp['hits']['total']['value']} 个文档。")
for hit in search_resp['hits']['hits']:
print(f"文档ID: {hit['_id']}, 内容: {hit['_source']}")
# 更新一个文档
update_body = {
"doc": {
"text": "Python操作Elasticsearch确实很方便,而且功能强大。"
}
}
update_resp = es.update(index="my_index", id=1, body=update_body)
print(f"更新文档结果: {update_resp['result']}")
# 删除一个文档
delete_resp = es.delete(index="my_index", id=1)
print(f"删除文档结果: {delete_resp['result']}")上面这些基础操作,涵盖了增删改查的核心功能。你会发现,
elasticsearch-py
在实际生产环境中,Elasticsearch通常以集群形式部署,而且为了安全,往往会启用认证。这时候,仅仅连接
localhost:9200
连接远程集群,你需要指定Elasticsearch节点的地址列表。如果集群启用了HTTPS,那SSL/TLS配置就显得尤为重要。
from elasticsearch import Elasticsearch
import ssl
# 假设你的Elasticsearch集群节点地址
# 如果是云服务,比如Elastic Cloud,地址会更复杂,通常是带端口的域名
es_hosts = [
{'host': 'your_es_host1.com', 'port': 9200},
{'host': 'your_es_host2.com', 'port': 9200},
]
# 如果启用了HTTPS,并且需要验证证书
# ca_certs: 你的CA证书路径,用于验证Elasticsearch服务器的身份
# verify_certs: 是否验证服务器证书
# ssl_show_warn: 如果为True,当证书验证失败时会打印警告
context = ssl.create_default_context(cafile="/path/to/your/ca.crt")
# 如果不需要验证服务器证书(不推荐在生产环境使用)
# context = ssl._create_unverified_context()
# 处理基本认证 (用户名和密码)
# 也可以通过http_auth=('username', 'password')参数直接传入
username = 'elastic'
password = 'your_password'
try:
es = Elasticsearch(
es_hosts,
# scheme="https", # 如果默认是http,需要明确指定https
# use_ssl=True, # 早期版本可能需要,现在通常根据scheme自动判断
# verify_certs=True, # 是否验证证书
# ssl_context=context, # 传入SSL上下文
http_auth=(username, password),
timeout=30 # 设置连接超时,防止长时间等待
)
if es.ping():
print("成功连接到受认证的Elasticsearch集群!")
else:
print("无法连接到Elasticsearch集群,请检查配置或认证信息。")
except Exception as e:
print(f"连接Elasticsearch集群时发生错误: {e}")
# 连接时,如果遇到连接超时或者认证失败,这些错误都会在这里被捕获。
# 实际操作中,这些参数需要根据你的Elasticsearch部署情况来配置。
# 特别是证书路径和认证信息,务必保密。我个人经验是,
ssl_context
cafile
以上就是Python如何操作Elasticsearch?elasticsearch-py的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号