Setup#
Let create a domain
Then select test environment which create 1 node
Then select software version
Next, let make it public accessible
Finally, setup permission and authentication
Simple demo with only use fine-grained access control
Go to the domain dashboard and update permissions
Client#
First install dependencies, here is requirements.txt
boto3==1.26.25boto3-stubs==1.24.26botocore==1.29.25botocore-stubs==1.27.42.post1requests-aws4auth==1.1.2opensearch-py==2.0.0
Authentication (singnature v4)
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuthimport boto3import os# load oss urlfrom dotenv import load_dotenvload_dotenv(".demo.env")# credentialsservice = 'es'# service = 'aoss' for serverlessregion = 'us-east-1'credentials = boto3.Session().get_credentials()# create a clientawsauth = AWSV4SignerAuth(credentials, region=region)client = OpenSearch(hosts=[{'host': os.environ["OSS_URL"], 'port': 443}],http_auth=awsauth,use_ssl=True,verify_certs=True,connection_class=RequestsHttpConnection,timeout=300)
Operation#
Let query an index
# query indexresponse = client.search(index="cdk-entest",body={"query": {"query_string": {"query": "Hello"}}})print(response)
Let write a function to index data
# index datadef test_index_data(host):""""""client = OpenSearch(hosts=[{'host': host, 'port': 443}],http_auth=awsauth,use_ssl=True,verify_certs=True,connection_class=RequestsHttpConnection,timeout=300)print(client)#response = client.index(index="cdk-entest",body={"title": "Hello","creator": "Larry David","year": 1989},id="1")print(response)
Let write a function to query data
# query indexdef test_query_index(host):""""""client = OpenSearch(hosts=[{'host': host, 'port': 443}],http_auth=awsauth,use_ssl=True,verify_certs=True,connection_class=RequestsHttpConnection,timeout=300)print(client)#response = client.search(index="cdk-entest",body={"query": {"query_string": {"query": "Hello"}}})print(response)