Python/FastAPI中使用Elasticsearch的方法笔记

    ローカル環境で起動中のElasticsearchにPythonで接続・操作する方法についてメモする。

事前准备 (shì

库安装 (Kù

pip install 'elasticsearch<7.14.0'

如果未指定版本,则会引发UnsupportedProductError错误(elasticsearch.UnsupportedProductError:客户端注意到服务器不是Elasticsearch,我们不支持这个未知产品)。

Elasticsearch准备就绪

こちらの手順でElasticsearchコンテナを起動しておく。

样品API代码

    app.py
from fastapi import FastAPI
from elasticsearch import Elasticsearch

app = FastAPI()

@app.get("/indices")
def indices():
    # Connect to Local Elasticsearch
    es = Elasticsearch(
        "http://localhost:9200",
        # Your Credentials
        http_auth=("elastic", "P@ssw0rd")
    )

    # Getting Indices
    indices = es.cat.indices(index='*', h='index').splitlines()

    # Showing Indices
    for index in indices:
        print(index)

    # Close Connection
    es.close()
    return {"indices": indices}

确认行动

    サンプルAPI起動
  uvicorn app:app --reload
  INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
  INFO:     Started reloader process [29459] using statreload
  INFO:     Started server process [29464]
  INFO:     Waiting for application startup.
  INFO:     Application startup complete.
    リクエスト
  GET /indices HTTP/1.1
  Host: 127.0.0.1:8000
    レスポンス
  {
      "indices": [
          ".monitoring-kibana-7-2022.02.19",
          ".security-7",
          "test-index",
          ".apm-custom-link",
          ".kibana_task_manager_1",
          ".kibana-event-log-7.11.1-000001",
          ".apm-agent-configuration",
          ".monitoring-es-7-2022.02.19",
          ".kibana_1"
      ]
  }

获取索引列表

请提供参考资料

    Python Elasticsearch 基本的な使い方まとめ
bannerAds