-
Notifications
You must be signed in to change notification settings - Fork 3
/
example.py
70 lines (55 loc) · 1.79 KB
/
example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
#
# Modifications Copyright OpenSearch Contributors. See
# GitHub history for details.
import logging
from os import environ
from time import sleep
from urllib.parse import urlparse
from boto3 import Session
from opensearchpy import Urllib3AWSV4SignerAuth, OpenSearch, __versionstr__
# verbose logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
print(f"Using opensearch-py {__versionstr__}")
# cluster endpoint, for example: my-test-domain.us-east-1.es.amazonaws.com
url = urlparse(environ['ENDPOINT'])
region = environ.get('AWS_REGION', 'us-east-1')
service = environ.get('SERVICE', 'es')
credentials = Session().get_credentials()
auth = Urllib3AWSV4SignerAuth(credentials, region, service)
client = OpenSearch(
hosts=[{
'host': url.netloc,
'port': url.port or 443
}],
http_auth=auth,
use_ssl=True,
verify_certs=True,
timeout=30
)
# TODO: remove when OpenSearch Serverless adds support for /
if service == 'es':
info = client.info()
print(f"{info['version']['distribution']}: {info['version']['number']}")
# create an index
index = 'movies'
client.indices.create(index=index)
try:
# index data
document = {'director': 'Bennett Miller', 'title': 'Moneyball', 'year': 2011}
client.index(index=index, body=document, id='1')
# wait for the document to index
sleep(1)
# search for the document
results = client.search(body={'query': {'match': {'director': 'miller'}}})
for hit in results['hits']['hits']:
print(hit['_source'])
# delete the document
client.delete(index=index, id='1')
finally:
# delete the index
client.indices.delete(index=index)