検索
ホームページバックエンド開発Python チュートリアルPython を使用して AWS OpenSearch または Elasticsearch クラスターに接続する方法

How to connect to AWS OpenSearch or Elasticsearch clusters using python

Python を使用して AWS で実行されている OpenSearch (ES) サービスに接続するのは面倒です。オンラインで見つけたサンプルのほとんどは機能しないか古いため、常に同じ問題を修正することになります。時間とストレスを軽減するために、2024 年 12 月時点で最新の実用的なコード スニペットのコレクションをここに示します。

  • opensearch-py ライブラリ (OpenSearch ElasticSearch) を使用して接続します
  • elasticsearch ライブラリを使用して接続する (ElasticSearch のみ)
    • エラスティックサーチ >= 8
    • エラスティックサーチ

opensearch-py ライブラリ (OpenSearch ElasticSearch) を使用して接続する

これは、AWS によって管理される ES インスタンスに接続するための私の推奨の方法です。 ElasticSearch クラスターと OpenSearch クラスターの両方で機能し、認証には AWS プロファイルを利用できます。

opensearch-py と boto3 をインストールします (認証用):

pip install opensearch-py boto3

この記事の執筆時点では、これにより opensearch-py==2.8.0 と boto3==1.35.81 がインストールされます。

これで、次を使用してクライアントを作成できます:

import boto3

from opensearchpy import (
    AWSV4SignerAuth,
    OpenSearch,
    RequestsHttpConnection,
)

es_host = "search-my-aws-esdomain-5k2baneoyj4vywjseocultv2au.eu-central-1.es.amazonaws.com"
aws_access_key = "AKIAXCUEGTAF3CV7GYKA"
aws_secret_key = "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"
region = "eu-central-1"

# Note: you can also use boto3.Session(profile_name="my-profile") or other ways
session = boto3.Session(
    aws_access_key_id=aws_access_key,
    aws_secret_access_key=aws_secret_key,
    region_name=region,
)

client = OpenSearch(
    hosts=[{"host": es_host, "port": 443}],
    http_auth=AWSV4SignerAuth(session.get_credentials(), region, "es"),
    connection_class=RequestsHttpConnection,
    use_ssl=True,
)

boto3.Session は、プロファイルや環境変数の使用など、セッションを作成するさまざまな方法をサポートしていることに注意してください。チェックさせていただきます!

入手したら、以下を使用して接続を確認します。

client.ping() # should return True
client.info() # use this to get a proper error message if ping fails

インデックスを確認するには:

# List all indices
client.cat.indices()
client.indices.get("*")

# Check the existence of an indice
client.indices.exists("my-index")

elasticsearch ライブラリを使用して接続する (ElasticSearch のみ)

?これはElasticSearch クラスターでのみ機能します! OpenSearch クラスターに接続すると、

が発生します

UnsupportedProductError: クライアントは、サーバーが Elasticsearch ではないことに気づきました。この不明な製品はサポートされていません

elasticsearch >= 8

ほとんどのスニペットは、elasticsearch 8.X で削除されたクラスである RequestsHttpConnection を依然として参照しています。 「elasticsearch」から「RequestsHttpConnection」という名前をインポートできないというエラーを検索していた場合は、正しい場所にいます。

elasticsearch (これにより elastic-transport もインストールされるはずです) と request_aws4auth をインストールします。後者は、リクエストに基づいて、AWS への認証を処理するために必要です:

pip install elasticsearch requests-aws4auth

この記事の執筆時点では、これにより elastic-transport==8.15.1、elasticsearch==8.17.0、およびrequests-aws4auth==1.3.1がインストールされます。

これで、次を使用してクライアントを作成できます:

from elastic_transport import RequestsHttpNode
from elasticsearch import Elasticsearch
from requests_aws4auth import AWS4Auth

es_endpoint = "search-my-aws-esdomain-5k2baneoyj4vywjseocultv2au.eu-central-1.es.amazonaws.com"
aws_access_key = "AKIAXCUEGTAF3CV7GYKA"
aws_secret_key = "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"
region = "eu-central-1"

es = Elasticsearch(
    f"https://{es_host}",
    http_auth=AWS4Auth(
        aws_access_key, 
        aws_secret_key, 
        region,
        "es",
    ),
    verify_certs=True,
    node_class=RequestsHttpNode,
)

入手したら、以下を使用して接続を確認します。

es.ping() # should return True
es.info() # use this to get a proper error message if ping fails

elasticsearch

まだ古いバージョンの elasticsearch を使用している場合:

pip install "elasticsearch



<p>現在 elasticsearch==7.17.12、requests-aws4auth==1.3.1.</p>

<p>これで、次を使用してクライアントを作成できます:<br>
</p><pre class="brush:php;toolbar:false">pip install opensearch-py boto3

接続を確認してください:

import boto3

from opensearchpy import (
    AWSV4SignerAuth,
    OpenSearch,
    RequestsHttpConnection,
)

es_host = "search-my-aws-esdomain-5k2baneoyj4vywjseocultv2au.eu-central-1.es.amazonaws.com"
aws_access_key = "AKIAXCUEGTAF3CV7GYKA"
aws_secret_key = "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"
region = "eu-central-1"

# Note: you can also use boto3.Session(profile_name="my-profile") or other ways
session = boto3.Session(
    aws_access_key_id=aws_access_key,
    aws_secret_access_key=aws_secret_key,
    region_name=region,
)

client = OpenSearch(
    hosts=[{"host": es_host, "port": 443}],
    http_auth=AWSV4SignerAuth(session.get_credentials(), region, "es"),
    connection_class=RequestsHttpConnection,
    use_ssl=True,
)

以上がPython を使用して AWS OpenSearch または Elasticsearch クラスターに接続する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Pythonリストをどのようにスライスしますか?Pythonリストをどのようにスライスしますか?May 02, 2025 am 12:14 AM

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

Numpyアレイで実行できる一般的な操作は何ですか?Numpyアレイで実行できる一般的な操作は何ですか?May 02, 2025 am 12:09 AM

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Pythonを使用したデータ分析では、配列はどのように使用されていますか?Pythonを使用したデータ分析では、配列はどのように使用されていますか?May 02, 2025 am 12:09 AM

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?リストのメモリフットプリントは、Pythonの配列のメモリフットプリントとどのように比較されますか?May 02, 2025 am 12:08 AM

listsandnumpyarraysinpythonhavedifferentmemoryfootprints:listsaremoreflexiblellessmemory-efficient、whileenumpyarraysaraysareoptimizedfornumericaldata.1)listsstorereferencesto objects、with whowedaround64byteson64-bitedatigu

実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?実行可能なPythonスクリプトを展開するとき、環境固有の構成をどのように処理しますか?May 02, 2025 am 12:07 AM

toensurepythonscriptsbehaveCorrectlyAcrossDevelosment、staging、and Production、usetheseStrategies:1)環境variablesforsimplestetings、2)configurationfilesforcomplexsetups、and3)dynamicloadingforadaptability.eachtododododododofersuniquebentandrequiresca

Pythonアレイをどのようにスライスしますか?Pythonアレイをどのようにスライスしますか?May 01, 2025 am 12:18 AM

Pythonリストスライスの基本的な構文はリストです[start:stop:step]。 1.STARTは最初の要素インデックス、2。ストップは除外された最初の要素インデックスであり、3.ステップは要素間のステップサイズを決定します。スライスは、データを抽出するためだけでなく、リストを変更および反転させるためにも使用されます。

どのような状況で、リストは配列よりもパフォーマンスが向上しますか?どのような状況で、リストは配列よりもパフォーマンスが向上しますか?May 01, 2025 am 12:06 AM

ListSoutPerformArraysIn:1)ダイナミシジョンアンドフレーケンティオン/削除、2)ストーリングヘテロゼンダタ、および3)メモリ効率の装飾、ButmayhaveslightPerformancostsinceNASOPERATIONS。

PythonアレイをPythonリストに変換するにはどうすればよいですか?PythonアレイをPythonリストに変換するにはどうすればよいですか?May 01, 2025 am 12:05 AM

toconvertapythonarraytoalist、usetheList()constructororageneratorexpression.1)importhearraymoduleandcreateanarray.2)useList(arr)または[xforxinarr] toconvertoalistは、largedatatessを変えることを伴うものです。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

MantisBT

MantisBT

Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール