2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python/FastAPIからのElasticsearch利用方法メモ

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

事前準備

ライブラリインストール

pip install 'elasticsearch<7.14.0'

※バージョン指定しないとraise UnsupportedProductError( elasticsearch.UnsupportedProductError: The client noticed that the server is not Elasticsearch and we do not support this unknown productなるエラーが出力された。

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"
        ]
    }
    

    ※インデックス一覧が取得される

参考情報

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?