'How to use AsyncElasticsearch Connection Pool in FastApi?

The relevant parts of my code are as follows:

@app.on_event("startup")
async def startup():
    es = Translator()
    app.state.es_conn = es.connect()


@app.on_event('shutdown')
async def shutdown_event():
    es = Translator()
    await es.close(app.state.es_conn)


@app.post('/query')
async def query(req: Request):
    es = Translator()
    es.set_conn(req.app.state.es_conn)

    return await es.search()


from elasticsearch import AsyncElasticsearch, AsyncTransport

class Translator(object):
    def __init__(self):
        self.__es = None

    def connect(self):
        return AsyncElasticsearch(
            hosts='http://192.168.0.2:9200/',
            transport_class=AsyncTransport)

    def set_conn(self, conn):
        self.__es = conn

    async def close(self, conn):
        await conn.close()
        self.__es = None

    async def search(self):
        return await self.__es.search(index=index, body=body)

It runs in the following environment:

  • PyPy 7.3.7
  • fastapi 0.73.0
  • Elasticsearch 7.10.1

My question are:

  1. Although the code can work normally, how can I detect whether it uses connection pool?
  2. How to use connection pool correctly when asynchronous?

Can anyone help me? Thank you!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source