


Connecting to an OpenSearch (ES) service running in AWS using Python is painful. Most examples I find online either don't work or are outdated, leaving me constantly fixing the same issues. To save time and frustration, here’s a collection of working code snippets, up-to-date as of December 2024.
- Connect using the opensearch-py library (OpenSearch ElasticSearch)
-
Connect using the elasticsearch library (ElasticSearch only)
- elasticsearch >= 8
- elasticsearch
Connect using the opensearch-py library (OpenSearch ElasticSearch)
This is my preferred way of connecting to an ES instance managed by AWS. It works for both ElasticSearch and OpenSearch clusters, and the authentication can take advantage of AWS profiles.
Install opensearch-py and boto3 (for authentication):
pip install opensearch-py boto3
At the time of writing, this installs opensearch-py==2.8.0 and boto3==1.35.81.
Now, you can create a client using the following:
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, )
Note that boto3.Session supports various ways of creating a session: using a profile, environment variables, and more. I will let you check it out!
Once you have it, check the connection using:
client.ping() # should return True client.info() # use this to get a proper error message if ping fails
To check indices:
# List all indices client.cat.indices() client.indices.get("*") # Check the existence of an indice client.indices.exists("my-index")
Connect using the elasticsearch library (ElasticSearch only)
? This only works for ElasticSearch clusters! Connecting to an OpenSearch cluster raises
UnsupportedProductError: The client noticed that the server is not Elasticsearch and we do not support this unknown product
elasticsearch >= 8
Most snippets are still referencing RequestsHttpConnection, a class that was removed in elasticsearch 8.X. If you were googling for the error cannot import name 'RequestsHttpConnection' from 'elasticsearch’, you are at the right place!
Install elasticsearch (this should install elastic-transport as well), and requests_aws4auth . The latter, based on requests, is required to handle authentication to AWS:
pip install elasticsearch requests-aws4auth
At the time of writing, this installs elastic-transport==8.15.1, elasticsearch==8.17.0 and requests-aws4auth==1.3.1.
Now, you can create a client using the following:
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, )
Once you have it, check the connection using:
es.ping() # should return True es.info() # use this to get a proper error message if ping fails
elasticsearch
If you are still on an old version of elasticsearch:
pip install "elasticsearch <p>Currently elasticsearch==7.17.12, requests-aws4auth==1.3.1.</p> <p>Now, you can create a client using the following:<br> </p><pre class="brush:php;toolbar:false">pip install opensearch-py boto3
Check the connection:
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, )
The above is the detailed content of How to connect to AWS OpenSearch or Elasticsearch clusters using python. For more information, please follow other related articles on the PHP Chinese website!

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version
SublimeText3 Linux latest version
