Elasticsearch Python 客户端¶
Elasticsearch官方低级客户端。它的目标是提供共同的 使用Python语言编写所有与Elasticsearch相关的代码;正因为如此,它尝试 不受意见影响,并且非常具有可扩展性。
安装¶
安装elasticsearch
包装包含pip:
$ python -m pip install elasticsearch
如果您的应用程序在Python中使用异步/等待,则可以使用
这个async
额外的:
$ python -m pip install elasticsearch[async]
阅读有关以下内容的更多信息如何在此项目中使用Asyncio.
兼容性¶
该库与所有Elasticsearch版本兼容,因为0.90.x
但是你必须使用匹配的主版本:
For Elasticsearch 7.0.之后,使用主要版本7(7.x.y
))的
库。
For Elasticsearch 6.0.之后,使用主要版本6(6.x.y
))的
库。
For Elasticsearch 5.0之后,使用主要版本5(5.x.y
))的
库。
For Elasticsearch 2.0之后,使用主要版本2(2.x.y
))的
库,等等。
在中设置要求的推荐方式setup.py or requirements.txt is:
# Elasticsearch 7.x
elasticsearch>=7.0.0,<8.0.0
# Elasticsearch 6.x
elasticsearch>=6.0.0,<7.0.0
# Elasticsearch 5.x
elasticsearch>=5.0.0,<6.0.0
# Elasticsearch 2.x
elasticsearch>=2.0.0,<3.0.0
如果您需要同时安装多个旧版本
版本还发布为elasticsearch2
, elasticsearch5
and elasticsearch6
.
用法示例¶
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()
doc = {
'author': 'kimchy',
'text': 'Elasticsearch: cool. bonsai cool.',
'timestamp': datetime.now(),
}
res = es.index(index="test-index", id=1, body=doc)
print(res['result'])
res = es.get(index="test-index", id=1)
print(res['_source'])
es.indices.refresh(index="test-index")
res = es.search(index="test-index", body={"query": {"match_all": {}}})
print("Got %d Hits:" % res['hits']['total']['value'])
for hit in res['hits']['hits']:
print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])
功能¶
这个客户端被设计成非常薄的包装器,包裹着Elasticsearch的 restapi,以 允许最大限度的灵活性。这意味着在这件事上没有意见。 客户端;这也意味着一些API使用起来有点麻烦。 Python。我们创造了一些帮助者来帮助解决这个问题 更高级别的库(elasticsearch-dsl),以提供 使用Elasticsearch的一种更方便的方式。
持久连接¶
elasticsearch-py
在单个连接内使用持久连接
池(每个配置或嗅探的节点一个)。开箱即用,您可以选择
在两个人之间http
协议实施。看见传输类了解更多信息
信息。
传输层将创建所选连接类的实例
每个节点,并跟踪各个节点的运行状况-如果某个节点成为
无响应(连接时引发异常)超时
由ConnectionPool
类,并且只返回到
超时后的循环结束(或当没有活动节点时)。通过
在将默认节点传递到池和循环之前,会对其进行随机化
采用策略进行负载均衡。
您可以通过将参数传递给连接层API(所有关键字参数到Elasticsearch
类将通过)。如果什么
您想要完成的操作不受支持,您应该能够创建一个子类
,并将其作为要使用的参数传递,而不是
默认实现。
自动复古¶
如果与节点的连接因连接问题而失败(引发ConnectionError
)它被认为处于故障状态。它
将被暂时搁置dead_timeout
秒,请求将是
在另一个节点上重试。如果连接连续多次失败,
超时将逐渐变大,以避免命中所有节点
指示,向下。如果没有活动连接可用,则具有
将使用最小超时。
默认情况下,超时不会触发重试
(ConnectionTimeout
),设置retry_on_timeout
to
True
也可以在超时时重试。
Sniffing¶
客户端可以配置为检查群集状态,以获取
节点在启动时、定期和/或故障时。看见Transport
参数了解详细信息。
一些示例配置:
from elasticsearch import Elasticsearch # by default we don't sniff, ever es = Elasticsearch() # you can specify to sniff on startup to inspect the cluster and load # balance across all nodes es = Elasticsearch(["seed1", "seed2"], sniff_on_start=True) # you can also sniff periodically and/or after failure: es = Elasticsearch(["seed1", "seed2"], sniff_on_start=True, sniff_on_connection_fail=True, sniffer_timeout=60)
线程安全¶
客户端是线程安全的,可以在多线程环境中使用。最好的 实践是创建客户端的单个全局实例并使用它 在您的整个申请过程中。如果您的应用程序是长期运行的,请考虑 打开电源Sniffing要确保群集上的客户端是最新的,请执行以下操作 地点。
默认情况下,我们允许urllib3
要打开到每个节点的最多10个连接,请执行以下操作
您的应用程序需要更多的并行性,请使用maxsize
参数设置为
提高限制:
# allow up to 25 connections to each node
es = Elasticsearch(["host1", "host2"], maxsize=25)
备注
由于我们在整个客户端使用持久连接,这意味着
客户不能容忍fork
很好。如果您的应用程序需要
多个进程确保您在调用后创建新的客户端fork
。请注意,Python的multiprocessing
模块使用fork
至
在POSIX系统上创建新进程。
TLS/SSL和身份验证¶
您可以将客户端配置为使用SSL
用于连接到您的
elasticsearch集群,包括证书验证和http认证:
from elasticsearch import Elasticsearch
# you can use RFC-1738 to specify the url
es = Elasticsearch(['https://user:secret@localhost:443'])
# ... or specify common parameters as kwargs
es = Elasticsearch(
['localhost', 'otherhost'],
http_auth=('user', 'secret'),
scheme="https",
port=443,
)
# SSL client authentication using client_cert and client_key
from ssl import create_default_context
context = create_default_context(cafile="path/to/cert.pem")
es = Elasticsearch(
['localhost', 'otherhost'],
http_auth=('user', 'secret'),
scheme="https",
port=443,
ssl_context=context,
)
警告
elasticsearch-py
不附带默认的根证书集。至
要进行有效的SSL证书验证,您需要指定您自己的证书验证
作为cafile
or capath
or cadata
或安装certifi它将会
会被自动取走。
请参阅类Urllib3HttpConnection
有关详细信息,请参阅
选项说明。
通过云ID接入¶
云ID是配置您的客户端以使其正常工作的一种简单方法
借助您的弹性云部署。将这两个选项组合在一起cloud_id
无论使用哪一种http_auth
or api_key
要进行身份验证,请执行以下操作
借助您的弹性云部署。
使用cloud_id
默认情况下启用TLS验证和HTTP压缩
并将端口设置为443
除非通过port
参数
或其中编码的端口值cloud_id
。使用云ID还会禁用嗅探。
from elasticsearch import Elasticsearch
es = Elasticsearch(
cloud_id="cluster-1:dXMa5Fx...",
http_auth=("elastic", "<password>"),
)
API密钥身份验证¶
您可以将客户端配置为使用Elasticsearch的API key用于连接到您的群集。
请注意,此身份验证方法已随Elasticsearch版本一起引入6.7.0
.
from elasticsearch import Elasticsearch
# you can use the api key tuple
es = Elasticsearch(
['node-1', 'node-2', 'node-3'],
api_key=('id', 'api_key'),
)
# or you pass the base 64 encoded token
es = Elasticsearch(
['node-1', 'node-2', 'node-3'],
api_key='base64encoded tuple',
)
日志¶
elasticsearch-py
使用标准伐木库从python到定义
两个伐木者:elasticsearch
and elasticsearch.trace
. elasticsearch
由客户端用来记录标准活动,具体取决于日志级别。elasticsearch.trace
可用于在表单中记录对服务器的请求
的curl
使用打印精美的json的命令,然后可以从
命令行。因为它是为共享而设计的(例如,为了演示
一个问题)它也只是用localhost:9200
作为地址,而不是
主机的实际地址。如果尚未配置跟踪记录器
它已经设置为传播=FALSE=FALSE所以它需要单独激活。
类型提示¶
开始于elasticsearch-py
该库现在随附的v7.10.0类型提示并使用如下工具支持基本的静态类型分析Mypy and Pyright.
如果我们编写的脚本存在类型错误,如使用request_timeout
使用
一个str
参数,而不是float
然后在脚本上运行Mypy:
# script.py
from elasticsearch import Elasticsearch
es = Elasticsearch(...)
es.search(
index="test-index",
request_timeout="5" # type error!
)
# $ mypy script.py
# script.py:5: error: Argument "request_timeout" to "search" of "Elasticsearch" has
# incompatible type "str"; expected "Union[int, float, None]"
# Found 1 error in 1 file (checked 1 source file)
目前,API方法的许多参数类型并不特定于
一种类型(它们是一种类型)typing.Any
)但在未来
它们将被收紧,以便更好地进行静态类型检查。
类型提示还允许IDE等工具检查类型并提供更好的 自动完成功能。
警告
API方法的类型提示,如search
与函数签名不匹配
可以在源代码中找到。类型提示表示对
API方法。强烈建议使用关键字参数,因此所有可选参数
和body
在类型提示中仅限关键字。
JetBrains PyCharm将使用该警告Unexpected argument
以表示
参数可以是仅关键字。
环境方面的考虑因素¶
使用客户端时,您的环境有几个限制, 可能会发挥作用。
使用HTTP负载平衡器时,不能使用Sniffing功能-群集将向客户端提供以下IP地址 直接连接到集群,绕过负载均衡。取决于 您的配置这可能是您不想要的东西,或者完全损坏。
压缩¶
使用容量受限的网络(低吞吐量)时,启用 压缩。这在执行大容量装载或插入大型 文件。这将配置压缩。
from elasticsearch import Elasticsearch
es = Elasticsearch(hosts, http_compress=True)
通过连接到弹性云时默认启用压缩cloud_id
.
在带有IAM的AWS上运行¶
如果您想在AWS上使用此客户端进行基于IAM的身份验证,您可以使用 这个requests-aws4auth套餐:
from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
host = 'YOURHOST.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())
自定义¶
自定义序列化程序¶
默认情况下,JSONSerializer用于对所有传出请求进行编码。 但是,您可以实现自己的自定义序列化程序
from elasticsearch.serializer import JSONSerializer
class SetEncoder(JSONSerializer):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
if isinstance(obj, Something):
return 'CustomSomethingRepresentation'
return JSONSerializer.default(self, obj)
es = Elasticsearch(serializer=SetEncoder())
Elasticsearch-DSL¶
有关范围更有限的更高级别的客户端库,请查看elasticsearch-dsl-更多的python IC库位于elasticsearch-py
.
elasticsearch-dsl提供了一种更方便、更惯用的编写和操作方式查询通过镜像Elasticsearch JSON DSL的术语和结构 同时从Python公开整个DSL范围 直接使用定义的类或类似查询集的表达式。
它还提供了一个可选的持久层用于将文档处理为 以类似ORM的方式创建Python对象:定义映射、检索和保存 文档,将文档数据包装在用户定义的类中。
目录¶
- API文档
- X包API
- 异常
- 将Asyncio与Elasticsearch配合使用
- 连接层API
- 传输类
- 帮助者
- 更新日志
- 7.10.0(2020-11-11)
- 7.9.1(2020-08-19)
- 7.9.0(2020-08-18)
- 7.8.1(2020-07-30)
- 7.8.0(2020-06-18)
- 7.7.1(2020-05-26)
- 7.7.0(2020-05-13)
- 7.6.0(2020-03-19)
- 7.5.1(2020-01-19)
- 7.5.0
- 7.1.0(2019-11-14)
- 7.0.5(2019-10-01)
- 7.0.4(2019-08-22)
- 7.0.3(2019-08-21)
- 7.0.2(2019-05-29)
- 7.0.1(2019-05-19)
- 7.0.0(2019-04-11)
- 6.8.1(2020-03-31)
- 6.8.0(2020-03-12)
- 6.3.0(2018-06-20)
- 6.2.0(2018-03-20)
- 6.1.1(2018-01-05)
- 6.1.0(2018-01-05)
- 6.0.0(2017-11-14)
- 5.5.0(2017-11-10)
- 5.4.0(2017-05-18)
- 5.3.0(2017-03-30)
- 5.2.0(2017-02-12)
- 5.1.0(2017-01-11)
- 5.0.1(2016-11-02)
- 5.0.0(2016-10-19)
- 2.4.0(2016-08-17)
- 2.3.0(2016-02-29)
- 2.2.0(2016-01-05)
- 2.1.0(2015-10-19)
- 2.0.0(2015-10-14)
- 1.8.0(2015-10-14)
- 1.7.0(2015-09-21)
- 1.6.0(2015-06-10)
- 1.5.0(2015-05-18)
- 1.4.0(2015-02-11)
- 1.3.0(2014-12-31)
- 1.2.0(2014-08-03)
- 1.1.1(2014-07-04)
- 1.1.0(2014-07-02)
- 1.0.0(2014-02-11)
- 0.4.4(2013-12-23)
- 0.4.3(2013-10-22)
- 0.4.2(2013-10-08)
- 0.4.1(2013-09-24)
许可¶
版权所有,2020年Elasticsearch B.V.
按照阿帕奇许可证2.0版(“许可证”)获得许可; 除非遵守许可证,否则您不能使用此文件。 您可以在以下地址获取许可证副本
除非适用法律要求或书面同意,软件 在许可证下分发的是在“按原样”的基础上分发的, 没有任何明示或默示的保证或条件。 请参阅管理权限的特定语言的许可证和 许可证下的限制。