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 插件,可以幫助測試您的程式碼。它提供了您需要的大量樣板代碼。
請參閱我們的文件以取得完整文件。
歡迎對此項目做出貢獻。如果您有興趣貢獻,請參閱我們的貢獻指南