扁平化网站布局,北京电商网站建设哪家好,下载类网站 建设方案,给公司建网站 深圳作者#xff1a;来自 Elastic Quentin_Pradet
在这篇文章中#xff0c;我们将进行一些实验#xff0c;看看 Python Elasticsearch 客户端是否与新的 Python 3.13 自由线程#xff08;free-threading#xff09;版本兼容#xff0c;其中 GIL 已被删除。 介绍
但首先来自 Elastic Quentin_Pradet
在这篇文章中我们将进行一些实验看看 Python Elasticsearch 客户端是否与新的 Python 3.13 自由线程free-threading版本兼容其中 GIL 已被删除。 介绍
但首先什么是 GIL全局解释器锁 (Global Interpreter Lock - GIL) 是一个保护对 Python 对象访问的互斥锁可防止多个线程同时执行 Python 字节码。在实践中这并不总是一个问题。
科学编程可以使用不包含 GIL 的库如 NumPy。有些程序不是 CPU 密集型的而是 I/O 密集型的。例如如果你的代码向 Elasticsearch 发出昂贵的请求但不会对结果进行昂贵的计算则它可以有效地使用多个线程。事实上即使只有一个线程正在执行它也不会阻塞等待 I/O 的其他线程从而不会阻塞 GIL。 这也是 async/await 在 Python 中大放异彩的场景。
然而几十年来人们的目标一直是消除这一限制并实现真正的多线程编程。感谢 Sam Gross 的出色工作现在这一切成为了可能这项工作最初被称为 nogil但现在被称为 free-threading。虽然现有的纯 Python 代码与生成的构建仍然以相同的方式工作尽管目前单线程代码速度较慢但从 C 或 Rust 等其他语言编译的所有代码都需要重构。在过去这种向后不兼容的变化足以成为发布 Python 4 的理由。然而Python 3 迁移导致了超过 10 年的语言分裂由此造成的痛苦仍然历历在目。因此目前的计划是逐步推出
作为第 1 阶段当前阶段的一部分Python 3.13 提供了实验性的自由线程版本每个库和应用程序都需要测试它们的兼容性。在第二阶段这些构建将不再被称为 “实验性的”。在第 3 阶段标准 Python 构建将包括自由线程支持。
Elasticsearch Python 客户端是纯 Python 代码不涉及太多线程或特定依赖垃圾收集器因此它应该可以与自由线程构建一样好地运行。但是它确实具有受影响的可选依赖项例如 aiohttp 或 orjson。
我们将测试这些不同的部件看看它们是否正常工作。基准测试将作为练习留给读者 使用自由线程 Python
有多种方法可以安装自由线程的 Python 版本。我们将使用 Astral 的 uv 包管理器它允许使用 --python 3.13t 指定自由线程构建。 Astral 为 python-build-standalone 贡献了自由线程构建如果需要uv 将会使用它们
$ uv run --python 3.13t python
Using CPython 3.13.0
Creating virtual environment at: .venv
Installed 4 packages in 16ms
Python 3.13.0 experimental free-threading build (main, Oct 16 2024, 08:24:33)
[Clang 18.1.8 ] on darwin
Type help, copyright, credits or license for more information.但是如果你已经安装了自由线程解释器uv 将使用它而不是 python-build-standalone。例如如果你想在 macOS 上使用 Homebrew 提供的构建使用 brew install python-freethreading 安装你将得到以下输出
$ uv run --python 3.13t python
Using CPython 3.13.0 interpreter at:
/opt/homebrew/opt/python-freethreading/bin/python3.13t
Creating virtual environment at: .venv
Installed 4 packages in 4ms
Python 3.13.0 experimental free-threading build (main, Oct 7 2024, 05:02:14)
[Clang 16.0.0 (clang-1600.0.26.4)] on darwin
Type help, copyright, credits or license for more information.由于 uv 还支持内联脚本元数据标准我们将提供如下独立的代码片段
# /// script
# requires-python 3.13
# dependencies [
# numpy,
# ]
# ///
import numpy as npc np.arange(24).reshape(2, 3, 4)
你可以运行它们而不必担心虚拟环境或手动安装依赖项
$ uv run --python 3.13t example.py
Reading inline script metadata from example.py
[[[ 0 1 2 3][ 4 5 6 7][ 8 9 10 11]][[12 13 14 15][16 17 18 19][20 21 22 23]]] 使用 Elasticsearch
得益于 start-local 脚本Elasticsearch 同样易于运行
$ curl -fsSL https://elastic.co/start-local | sh______ _ _ _| ____| | | | (_)| |__ | | __ _ ___| |_ _ ___| __| | |/ _ / __| __| |/ __|| |____| | (_| \__ \ |_| | (__|______|_|\__,_|___/\__|_|\___|
-------------------------------------------------Run Elasticsearch and Kibana for local testing
-------------------------------------------------ℹ️ Do not use this script in a production environment⌛️ Setting up Elasticsearch and Kibana v8.16.0...- Generated random passwords
- Created the elastic-start-local folder containing the files:- .env, with settings- docker-compose.yml, for Docker services- start/stop/uninstall commands
- Running docker compose up --wait Congrats, Elasticsearch and Kibana are installed and running in Docker! Open your browser at http://localhost:5601Elasticsearch API endpoint: http://localhost:9200
我们来测试一下
# /// script
# requires-python 3.13
# dependencies [
# elasticsearch,
# ]
# ///
import os
import sysfrom elasticsearch import Elasticsearchprint(sys.version)
client Elasticsearch(http://localhost:9200, api_keyos.environ[ES_LOCAL_API_KEY]
)
print(client.info()[tagline])
虽然 start-local 不使用 HTTPS但它确实设置了身份验证。相关机密存储在 elastic-start-local/.env 文件中因此我们可以获取它并将 ES_LOCAL_API_KEY 作为环境变量传递
$ source elastic-start-local/.env
$ ES_LOCAL_API_KEY$ES_LOCAL_API_KEY uv run --python 3.13t ex1.py
Reading inline script metadata from ex1.py
3.13.0 experimental free-threading build (main, Oct 16 2024, 08:24:33)
[Clang 18.1.8 ]
You Know, for Search
太棒了一个简单的查询就按预期工作了。现在让我们测试 Python 客户端的其他区域。 批量助手 - bulk helper
我们在 Python 客户端中明确使用线程的唯一地方是在 parallel_bulk 帮助程序中。让我们索引 books.csv 数据集并进行查询以查看是否有效。
# /// script
# requires-python 3.13
# dependencies [
# elasticsearch,
# ]
# ///
import csv
import os
import sys
import timefrom elasticsearch import Elasticsearch, helpersclient Elasticsearch(http://localhost:9200, api_keyos.environ[ES_LOCAL_API_KEY]
)mappings {properties: {Title: {type: text},Description: {type: text},Author: {type: text},Year: {type: date, format: yyyy},Published: {type: keyword},Rating: {type: scaled_float, scaling_factor: 100},}
}client.options(ignore_status[404]).indices.delete(indexbooks)
client.indices.create(indexbooks, mappingsmappings)
print(Created index)def generate_docs():with open(books.csv, newline) as csvfile:reader csv.DictReader(csvfile, delimiter;)for row in reader:yield {_index: books, **row}start time.perf_counter()
n, errors helpers.bulk(client, generate_docs())
end time.perf_counter()
print(fIndexed {n} books in {end - start:.1f} seconds.)client.indices.refresh(indexbooks)print(Searching for Stephen King:)
resp client.search(indexbooks, query{match: {Author: Stephen King}}
)
for hit in resp.body[hits][hits]:book hit[_source]description f{book[Author]} - {book[Title]} ({book[Year]})rating f{book[Ratings]} starsprint(f {description}: {rating})
脚本的输出显示我们确实在不到 2 秒的时间内索引了所有 82k 本书这比标准批量助手快大约 2 倍。
$ ES_LOCAL_API_KEY$ES_LOCAL_API_KEY uv run --python 3.13t ex2.py
Reading inline script metadata from ex2.py
Created index
Indexed 81828 books in 1.6 seconds.
Searching for Stephen King:Stephen King - THE ELEMENTS OF STYLE (2013): 5.00 starsStephen King - Star (Thorndike Core) (2021): 3.11 starsStephen King - Hearts in Atlantis (2017): 4.08 starsStephen King - Misery (Spanish Edition) (2016): 4.43 starsStephen King - The Dead Zone (2016): 4.40 starsStephen King - Another World (Thorndike Core) (2021): 3.78 starsStephen King - FROM A BUICK 8 (True first edition) (2017): 3.25 starsStephen King - Road Work (2017): 4.29 starsStephen King - Icon (Thorndike Core) (2021): 4.00 starsStephen King - Misery (2016): 4.43 starsaiohttp
Elasticsearch 的 Python 客户端通过两个 HTTP 客户端aiohttp 和 httpx支持 asyncio默认使用 aiohttp。虽然 aiohttp 尚未正式支持自由线程构建目前确实无法编译但可以通过设置 AIOHTTP_NO_EXTENSIONS1 在纯 Python 模式下使用它。虽然性能会较慢但可以与自由线程构建兼容。
关于测试没有太多需要测试的内容因为 asyncio 事件循环已经局限于单个线程。接下来让我们复用之前的示例但改用 asyncio
# /// script
# requires-python 3.13
# dependencies [
# elasticsearch[async],
# ]
# ///
import asyncio
import os
import sysfrom elasticsearch import AsyncElasticsearchprint(sys.version)async def main():async with AsyncElasticsearch(http://localhost:9200, api_keyos.environ[ES_LOCAL_API_KEY]) as client:info await client.info()print(info[tagline])asyncio.run(main())
由于 uv run 会动态安装依赖项因此我们需要定义 AIOHTTP_NO_EXTENSIONS 来运行。事实上脚本的行为符合预期
$ export AIOHTTP_NO_EXTENSIONS1
$ export ES_LOCAL_API_KEY$ES_LOCAL_API_KEY
$ uv run --python 3.13t ex3.py
Reading inline script metadata from ex3.py
3.13.0 experimental free-threading build (main, Oct 16 2024, 08:24:33
[Clang 18.1.8 ]
You Know, for Search 序列化和反序列化
Elasticsearch Python 客户端支持多个库来序列化或反序列化数据。出于性能原因他们经常使用本机代码并且这些库需要进行调整才能与自由线程构建配合使用。
orjson 允许快速序列化/反序列化 JSON但尚不支持自由线程构建甚至无法编译。
PyArrow 18 和 Pandas 2.2.3 支持自由线程构建。让我们通过进行 ES|QL 查询来重用书籍索引
# /// script
# requires-python 3.13
# dependencies [
# elasticsearch,
# pandas,
# pyarrow,
# ]
# ///
import csv
import os
import sys
import timeimport pandas as pd
from elasticsearch import Elasticsearch, helpersclient Elasticsearch(http://localhost:9200, api_keyos.environ[ES_LOCAL_API_KEY]
)print(Searching for Stephen King:)
resp client.esql.query(queryFROM books| WHERE Author Stephen King| SORT Rating DESC| LIMIT 10,formatarrow,
)
df resp.to_pandas(types_mapperpd.ArrowDtype)
print(df)
输出以下内容
$ PYTHON_GIL0 ES_LOCAL_API_KEY$ES_LOCAL_API_KEY uv run --python 3.13t ex4.py
Reading inline script metadata from ex4.py
Searching for Stephen King:Author ... Title Year
0 Stephen King ... Another World (Thorndike Core) 2021-01-01 00:00:00
1 Stephen King ... FROM A BUICK 8 (True first edition) 2017-01-01 00:00:00
2 Stephen King ... Hearts in Atlantis 2017-01-01 00:00:00
3 Stephen King ... Misery (Spanish Edition) 2016-01-01 00:00:00
4 Stephen King ... The Dark Tower: The Gunslinger 2017-01-01 00:00:00
5 Stephen King ... The Dead Zone 2016-01-01 00:00:00
6 Stephen King ... NIGHTMARES AND DREAMSCAPES 2017-01-01 00:00:00
7 Stephen King ... How writers write 2002-01-01 00:00:00
8 Stephen King ... THE ELEMENTS OF STYLE 2013-01-01 00:00:00
9 Stephen King ... Road Work 2017-01-01 00:00:00 请注意我必须设置 PYTHON_GIL0 来禁用以下警告我认为不应该发出该警告因为这些库确实支持自由线程构建。也许这个问题将在未来的版本中得到修复。 结论
总而言之自由线程构建的效果出奇地好许多重要的库已经支持自由线程。虽然仍然存在一些不受支持的库例如 orjson 或 Polars但它们是例外而不是规则。自由线程的前景光明我可以看到这些构建很快就会脱离实验状态。 但在这种情况发生之前我建议不要在生产中使用它们。
如果你想了解有关自由线程的更多信息https://py-free-threading.github.io/是一个很好的资源特别是更多资源页面链接到有用的学习材料。
回答我最初的问题是的Python Elasticsearch 客户端在自由线程下运行得很好 原文Dec 4th, 2024: [EN] Does the Elasticsearch Python client work with free-threading Python? - Advent Calendar - Discuss the Elastic Stack