使用 Python 連接到在 AWS 中運行的 OpenSearch (ES) 服務非常痛苦。我在網路上找到的大多數範例要么不起作用,要么已經過時,讓我不斷修復相同的問題。為了節省時間和減少挫折感,這裡提供了截至 2024 年 12 月最新的工作程式碼片段集合。
- 使用 opensearch-py 函式庫 (OpenSearch ElasticSearch) 連線
-
使用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,我們不支援此未知產品
彈性搜尋>= 8
大多數程式碼片段仍然引用 RequestsHttpConnection,該類別已在 elasticsearch 8.X 中刪除。如果您在Google上搜尋錯誤無法從“elasticsearch”匯入名稱“RequestsHttpConnection”,那麼您來對地方了!
安裝elasticsearch(這也應該安裝elastic-transport)和requests_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:
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中文網其他相關文章!

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

Inpython,ListSusedynamicMemoryAllocationWithOver-Asalose,而alenumpyArraySallaySallocateFixedMemory.1)listssallocatemoremoremoremorythanneededinentientary上,respizeTized.2)numpyarsallaysallaysallocateAllocateAllocateAlcocateExactMemoryForements,OfferingPrediCtableSageButlessemageButlesseflextlessibility。

Inpython,YouCansspecthedatatAtatatPeyFelemereModeRernSpant.1)Usenpynernrump.1)Usenpynyp.dloatp.dloatp.ploatm64,formor professisconsiscontrolatatypes。

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,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

WebStorm Mac版
好用的JavaScript開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境