fastapi 配置 es连接池
conifg
pip install fastapi elasticsearch[async]
code
from fastapi import FastAPI
from elasticsearch import Elasticsearch
from elasticsearch.helpers import async_client
app = FastAPI()
@app.on_event("startup")
async def startup_event():
# 配置Elasticsearch连接
es = Elasticsearch(
hosts=[{"host": "localhost", "port": 9200}],
# 使用自带的AsyncElasticsearch客户端
http_async_client=async_client,
# 指定连接池配置
connection_class=async_client.AiohttpConnection,
# 其他配置...
)
# 将客户端实例设置为全局变量
app.state.es_client = es
@app.get("/search")
async def search(query: str):
es_client = app.state.es_client
# 使用异步方法执行搜索
response = await es_client.search(index="your_index", query={"match": {"field": query}})
return response