Python客户端操作Elasticsearch

一.Python与Elasticsearch交互示例

这段代码是使用Python的elasticsearch模块与Elasticsearch进行交互的示例:

from elasticsearch import Elasticsearch

# 一.创建连接
# 建立到Elasticsearch的连接,指定主机和端口,设置请求超时时间为3600秒
es = Elasticsearch(hosts="http://localhost:9200").options(request_timeout=3600)

# 二.创建索引
# 创建一个名为 'news' 的索引。如果索引已存在,会忽略掉400错误(IndexAlreadyExistsException)
es.indices.create(index='news', ignore=400)

# 三.删除索引
# 删除名为 'news' 的索引。ignore=[400, 404] 表示忽略索引不存在(404)和索引被删除前存在(400)的错误。
result = es.indices.delete(index="news", ignore=[400, 404])

# 四.添加数据
# 向 'news' 索引中添加一条文档,文档ID为'3',内容为data字典中的数据
data = {"name": "莫慧汝", "sex": "女", "age": 24}
es.index(index="news", id='3', body=data)

# 五.修改数据
# 根据ID修改数据,将ID为'1'的文档的'arg'字段的值修改为25
data = {"doc": {'arg': 25}}
es.update(index="news", id="1", body=data)

# 根据条件修改数据,使用update_by_query来更新满足条件的文档
script = {
    "source": "ctx._source.province ='四川省'",
    "lang": "painless"
}
query = {
    "match": {
        "id": "0cb0643c4dab9b544299b11c4215aafb"
    }
}
data = {
    'script': script,
    'query': query
}
es.update_by_query(index="regulations", body=data)

# 六.删除数据
# 根据ID删除文档,从 'news' 索引中删除ID为'3'的文档
result = es.delete(index="news", id="3")

# 根据条件删除文档,使用delete_by_query来删除满足条件的文档
query = {
    "match": {
        "id": "0cb0643c4dab9b544299b11c4215aafb"
    }
}
data = {
    'query': query
}
es.delete_by_query(index="regulations", body=data)

# 七.全部查询
# 执行全文档查询,返回 'news' 索引中所有文档的查询结果
account_index = "news"
query = {
    'query': {
        'match_all': {}
    }
}
result = es.search(index=account_index, body=query)
for row in result['hits']['hits']:
    print(row)

二.代码逐行解释

1.创建连接

使用 Elasticsearch 类建立与 Elasticsearch 的连接。指定主机为 localhost,端口为 9200,并设置请求超时时间为 3600 秒。

2.创建索引

使用 es.indices.create 方法创建一个名为 'news' 的索引。ignore=400 表示忽略已存在的索引的错误(即索引已存在时不抛出异常)。

3.删除索引

使用 es.indices.delete 方法删除名为 'news' 的索引。ignore=[400, 404] 表示忽略索引不存在和索引被删除前存在的错误。

4.添加数据

使用 es.index 方法向 'news' 索引中添加一条文档。文档的 ID 为 '3',内容为 data 字典中的数据。

5.修改数据

使用 es.update 方法根据文档 ID 修改数据。在示例中,将 ID 为 '1' 的文档的 'arg' 字段的值修改为 25

6.条件修改数据

使用 es.update_by_query 方法根据条件(这里根据匹配 'id': '0cb0643c4dab9b544299b11c4215aafb')来更新文档。使用 Painless 脚本将匹配的文档的 'province' 字段设置为 '四川省'

lang 指定了脚本语言,这里是 "painless"。Painless 是 Elasticsearch 内置的一种安全的脚本语言,用于执行复杂的文档更新操作和查询操作。

7.删除数据

使用 es.delete 方法根据文档 ID 删除数据。在示例中,删除 'news' 索引中 ID 为 '3' 的文档。

8.条件删除数据

使用 es.delete_by_query 方法根据条件(这里根据匹配 'id': '0cb0643c4dab9b544299b11c4215aafb')来删除文档。

9.全部查询

使用 es.search 方法执行全文档查询。在示例中,执行一个匹配所有文档的查询,并遍历打印查询结果中的每个文档。

三.ES-King:ES GUI客户端

1.集群健康

包括健康、分片信息和Task如下:

2.核心指标

包括节点、集群系统、索引|分片、文档|存储|缓存、集群系统、段如下:

3.集群索引列表

刚才创建的索引名news如下:

参考文献

[1] Python Elasticsearch client:https://elasticsearch-py.readthedocs.io/en/v8.14.0/quickstart.html

[2] Python Elasticsearch Client:https://github.com/elastic/elasticsearch-py/blob/v8.14.0/docs/sphinx/index.rst

[3] elasticsearch-py:https://github.com/elastic/elasticsearch-py

[4] ES REST APIs:https://www.elastic.co/guide/en/elasticsearch/reference/current/rest-apis.html

[5] Linux下安装ElasticSearch和使用:https://zhuanlan.zhihu.com/p/700225380

[6] python操作elasticsearch:https://zhuanlan.zhihu.com/p/692832220

[7] elasticsearch之python操作:https://www.cnblogs.com/xingxia/p/elasticsearch_python.html

[8] ES-King:https://github.com/Bronya0/ES-King

[9] Elasticsearch 25 个必知必会的默认值:https://mp.weixin.qq.com/s/AjORpCgr0BBW78wdhXZ_Ow

[10] 36张图详解ElasticSearch原理+实战知识点:https://juejin.cn/post/7037374695045333000

NLP工程化(星球号)

连接Elasticsearch服务通常需要配置客户端以确保安全性和兼容性,特别是在使用HTTPS协议时。ElasticsearchPython客户端提供了多种配置选项来支持HTTPS连接。 ### 基本HTTPS连接 对于基本的HTTPS连接,如果Elasticsearch集群启用了SSL/TLS加密,但不需要客户端证书验证,可以简单地通过设置`use_ssl=True`参数来启用HTTPS。此外,为了确保连接的安全性,建议同时设置`verify_certs=True`以启用证书验证。这要求客户端信任Elasticsearch服务器的SSL证书,无论是通过CA签名的证书还是自签名证书的手动添加。 ```python from elasticsearch import Elasticsearch es = Elasticsearch( hosts=[{'host': 'localhost', 'port': 9200}], use_ssl=True, verify_certs=True ) print(es.info()) ``` ### 使用自签名证书 如果使用的是自签名证书,或者证书颁发机构不在操作系统的信任库中,则需要提供一个CA证书文件路径或目录,以便客户端能够验证Elasticsearch服务器的身份。这可以通过`ca_certs`参数指定CA证书的位置实现。 ```python es = Elasticsearch( hosts=[{'host': 'localhost', 'port': 9200}], use_ssl=True, verify_certs=True, ca_certs='/path/to/cacert.pem' ) print(es.info()) ``` ### 客户端证书认证 当Elasticsearch配置为要求客户端证书认证时,除了服务器端的证书验证外,还需要向客户端提供自己的证书和私钥。这可以通过`client_cert`和`client_key`参数完成,分别指向客户端证书文件和私钥文件的位置。 ```python es = Elasticsearch( hosts=[{'host': 'localhost', 'port': 9200}], use_ssl=True, verify_certs=True, client_cert='/path/to/client.crt', client_key='/path/to/client.key' ) print(es.info()) ``` ### IAM认证(AWS环境) 在AWS环境中,如果Elasticsearch服务配置了IAM角色认证,可以利用`requests-aws4auth`包来处理签名过程。这种方式允许使用AWS访问密钥对请求进行签名,从而实现对Elasticsearch服务的身份验证。 ```python from elasticsearch import Elasticsearch, RequestsHttpConnection from requests_aws4auth import AWS4Auth host = 'your-host.us-east-1.es.amazonaws.com' awsauth = AWS4Auth('YOUR_ACCESS_KEY', 'YOUR_SECRET_KEY', 'REGION', 'es') es = Elasticsearch( hosts=[{'host': host, 'port': 443}], http_auth=awsauth, use_ssl=True, verify_certs=True, connection_class=RequestsHttpConnection ) print(es.info()) # 输出Elasticsearch的信息,确认连接成功 ``` 以上示例展示了如何根据不同的安全需求配置Python客户端以通过HTTPS连接Elasticsearch服务。确保在实际部署时根据具体的环境和安全策略调整这些配置参数[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NLP工程化

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值