使用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
这个客户端库。它把底层的HTTP通信和Elasticsearch的RESTful API封装得相当好,让我们开发者能更专注于数据操作本身,而不是去操心那些网络请求的细节。可以说,它是连接Python应用和Elasticsearch的桥梁,而且用起来确实挺顺手的。
解决方案
要开始用
elasticsearch-py
,第一步自然是安装它:
pip install elasticsearch
安装好之后,就可以实例化客户端并开始操作了。连接本地的Elasticsearch实例通常非常简单:
立即学习“Python免费学习笔记(深入)”;
from elasticsearch import Elasticsearch# 默认连接到 localhost:9200es = 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的RESTful API调用映射得非常直观,参数名也基本保持一致,学起来不费劲。
如何连接Elasticsearch集群并处理认证?
在实际生产环境中,Elasticsearch通常以集群形式部署,而且为了安全,往往会启用认证。这时候,仅仅连接
localhost:9200
就远远不够了。我个人觉得,处理好连接和认证是项目上线前必须搞定的事情。
连接远程集群,你需要指定Elasticsearch节点的地址列表。如果集群启用了HTTPS,那SSL/TLS配置就显得尤为重要。
from elasticsearch import Elasticsearchimport 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
的配置有时候会比较绕,特别是当你的Elasticsearch集群使用了自签名证书时,你需要把对应的CA证书正确地提供给
cafile
以上就是Python如何操作Elasticsearch?elasticsearch-py的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1366934.html
微信扫一扫
支付宝扫一扫