Elasticsearch Async
Load and query an Elasticsearch knowledge base asynchronously, then close both clients with async_close().
Code
import asyncio
from agno.agent import Agent
from agno.knowledge.knowledge import Knowledge
from agno.vectordb.elasticsearch import Elasticsearch
vector_db = Elasticsearch(
index_name="recipe_async",
)
knowledge_base = Knowledge(
vector_db=vector_db,
)
agent = Agent(knowledge=knowledge_base)
async def main():
await knowledge_base.ainsert(
url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"
)
# Create and use the agent
await agent.aprint_response("How to make Tom Kha Gai", markdown=True)
# The async client holds an aiohttp session that Python will not close for you:
# skip this and the script exits with "ResourceWarning: Unclosed connector" and a
# leaked socket.
await vector_db.async_close()
if __name__ == "__main__":
asyncio.run(main())Usage
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activateInstall dependencies
uv pip install -U "elasticsearch[async]" pypdf openai agnoSet environment variables
export OPENAI_API_KEY=xxxRun Elasticsearch
docker run -d \
--name elasticsearch \
-p 9200:9200 \
-p 9300:9300 \
-e "discovery.type=single-node" \
-e "xpack.security.enabled=false" \
-e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
docker.elastic.co/elasticsearch/elasticsearch:9.1.0Run Agent
python async_elasticsearch_db.py