백엔드 개발 파이썬 튜토리얼 Python을 사용하여 AWS OpenSearch 또는 Elasticsearch 클러스터에 연결하는 방법

Python을 사용하여 AWS OpenSearch 또는 Elasticsearch 클러스터에 연결하는 방법

Dec 20, 2024 pm 08:49 PM

How to connect to AWS OpenSearch or Elasticsearch clusters using python

Python을 사용하여 AWS에서 실행되는 OpenSearch(ES) 서비스에 연결하는 것은 쉽지 않습니다. 온라인에서 찾은 대부분의 예는 작동하지 않거나 오래되어 동일한 문제를 지속적으로 해결하게 되었습니다. 시간과 불편함을 줄이기 위해 2024년 12월 기준 최신 작동 코드 조각 모음을 소개합니다.

  • opensearch-py 라이브러리(OpenSearch ElasticSearch)를 사용하여 연결
  • elasticsearch 라이브러리를 사용하여 연결(ElasticSearch에만 해당)
    • elasticsearch >= 8
    • 탄성 검색 < 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가 아니며 우리가 이 알 수 없는 제품을 지원하지 않는다는 것을 발견했습니다.

탄성 검색 >= 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 및 요청-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
로그인 후 복사

엘라스틱서치 < 8

아직 이전 버전의 Elasticsearch를 사용하고 계시다면:

pip install "elasticsearch<8" requests-aws4auth
로그인 후 복사

현재 elasticsearch==7.17.12, 요청-aws4auth==1.3.1.

이제 다음을 사용하여 클라이언트를 생성할 수 있습니다.

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 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 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? 중간 독서를 위해 Fiddler를 사용할 때 브라우저에서 감지되는 것을 피하는 방법은 무엇입니까? Apr 02, 2025 am 07:15 AM

Fiddlerevery Where를 사용할 때 Man-in-the-Middle Reading에 Fiddlereverywhere를 사용할 때 감지되는 방법 ...

10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? 10 시간 이내에 프로젝트 및 문제 중심 방법에서 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법? Apr 02, 2025 am 07:18 AM

10 시간 이내에 컴퓨터 초보자 프로그래밍 기본 사항을 가르치는 방법은 무엇입니까? 컴퓨터 초보자에게 프로그래밍 지식을 가르치는 데 10 시간 밖에 걸리지 않는다면 무엇을 가르치기로 선택 하시겠습니까?

Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Inversiting.com의 크롤링 메커니즘을 우회하는 방법은 무엇입니까? Apr 02, 2025 am 07:03 AM

Investing.com의 크롤링 전략 이해 많은 사람들이 종종 Investing.com (https://cn.investing.com/news/latest-news)에서 뉴스 데이터를 크롤링하려고합니다.

Python 3.6 피클 파일로드 오류 modulenotfounderRor : 피클 파일 '__builtin__'를로드하면 어떻게해야합니까? Python 3.6 피클 파일로드 오류 modulenotfounderRor : 피클 파일 '__builtin__'를로드하면 어떻게해야합니까? Apr 02, 2025 am 06:27 AM

Python 3.6에 피클 파일 로딩 3.6 환경 오류 : ModulenotFounderRor : nomodulename ...

SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유는 무엇입니까? SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유는 무엇입니까? Apr 02, 2025 am 06:45 AM

SCAPY 크롤러를 사용할 때 파이프 라인 파일을 작성할 수없는 이유에 대한 논의 지속적인 데이터 저장을 위해 SCAPY 크롤러를 사용할 때 파이프 라인 파일이 발생할 수 있습니다 ...

See all articles