Meilisearch Python SDK 为Meilisearch API 提供了异步和同步客户端。
使用哪个客户端取决于您的用例。如果您正在使用的代码库使用 asyncio,例如,如果您使用 FastAPI,请选择AsyncClient
,否则选择同步Client
。两个客户端的功能是相同的,区别在于AsyncClient
提供异步方法并使用AsyncIndex
及其自己的附加异步方法。另一方面, Client
提供阻塞方法,并使用带有自己阻塞方法的Index
。
建议使用虚拟环境来安装此软件包。创建并激活虚拟环境后,使用以下命令安装软件包:
pip install meilisearch-python-sdk
运行美丽搜索的方法有多种。选择最适合您的用例的一个,然后启动服务器。
以使用 Docker 为例:
docker pull getmeili/meilisearch:latest
docker run -it --rm -p 7700:7700 getmeili/meilisearch:latest ./meilisearch --master-key=masterKey
from meilisearch_python_sdk import AsyncClient
async with AsyncClient ( 'http://127.0.0.1:7700' , 'masterKey' ) as client :
index = client . index ( "books" )
documents = [
{ "id" : 1 , "title" : "Ready Player One" },
{ "id" : 42 , "title" : "The Hitchhiker's Guide to the Galaxy" },
]
await index . add_documents ( documents )
from meilisearch_python_sdk import Client
client = Client ( 'http://127.0.0.1:7700' , 'masterKey' )
index = client . index ( "books" )
documents = [
{ "id" : 1 , "title" : "Ready Player One" },
{ "id" : 42 , "title" : "The Hitchhiker's Guide to the Galaxy" },
]
index . add_documents ( documents )
服务器将返回一个更新 ID,可用于获取更新的状态。为此,您可以保存将文档添加到变量中的结果响应,这将是一个UpdateId
对象,并使用它来检查更新的状态。
update = await index . add_documents ( documents )
status = await client . index ( 'books' ). get_update_status ( update . update_id )
update = index . add_documents ( documents )
status = client . index ( 'books' ). get_update_status ( update . update_id )
search_result = await index . search ( "ready player" )
search_result = index . search ( "ready player" )
SearchResults (
hits = [
{
"id" : 1 ,
"title" : "Ready Player One" ,
},
],
offset = 0 ,
limit = 20 ,
nb_hits = 1 ,
exhaustive_nb_hits = bool ,
facets_distributionn = None ,
processing_time_ms = 1 ,
query = "ready player" ,
)
有关参数的信息可以在文档的搜索参数部分找到。
await index . search (
"guide" ,
attributes_to_highlight = [ "title" ],
filters = "book_id > 10"
)
index . search (
"guide" ,
attributes_to_highlight = [ "title" ],
filters = "book_id > 10"
)
SearchResults (
hits = [
{
"id" : 42 ,
"title" : "The Hitchhiker's Guide to the Galaxy" ,
"_formatted" : {
"id" : 42 ,
"title" : "The Hitchhiker's Guide to the <em>Galaxy</em>"
}
},
],
offset = 0 ,
limit = 20 ,
nb_hits = 1 ,
exhaustive_nb_hits = bool ,
facets_distributionn = None ,
processing_time_ms = 5 ,
query = "galaxy" ,
)
以下基准测试将该库与官方 Meilisearch Python 库进行了比较。请注意, AsyncClient
带来的所有性能提升都是通过利用 asyncio 来实现的。这意味着,如果您的代码没有利用 asyncio 或者它没有阻止事件循环,则不会看到这里的收益,并且客户端之间的性能将非常相似。
该测试比较了将 100 万个文档以 1000 个为一组发送到美丽搜索服务器进行索引所需的时间(越低越好)。该时间没有考虑 Meilisearch 索引文档所需的时间,因为这不属于库功能范围。
此测试比较完成 1000 次搜索所需的时间(越低越好)
Prashanth Rao 进行了一些独立测试,发现该异步客户端的数据摄取速度比同步客户端快约 30%。您可以在他的博客文章中找到关于他如何测试结果的详细记录。
pytest-meilisearch 是一个 pytest 插件,可以帮助测试您的代码。它提供了您需要的大量样板代码。
请参阅我们的文档以获取完整文档。
欢迎对此项目做出贡献。如果您有兴趣贡献,请参阅我们的贡献指南