To add the client to your project, install it using pip:
pip install opensearch-py
Then import it like any other module:
from opensearchpy import OpenSearch
For better performance we recommend the async client. See Asynchronous I/O for more information.
In general, we recommend using a package manager, such as poetry, for your projects. This is the package manager used for samples.
In the example below, we create a client, create an index with non-default settings, insert a document into the index, search for the document, delete the document, and finally delete the index.
You can find working versions of the code below that can be run with a local instance of OpenSearch in samples.
from opensearchpy import OpenSearch
host = 'localhost'
port = 9200
auth = ('admin', 'admin') # For testing only. Don't store credentials in code.
client = OpenSearch(
hosts = [{'host': host, 'port': port}],
http_auth = auth,
use_ssl = True,
verify_certs = False
)
info = client.info()
print(f"Welcome to {info['version']['distribution']} {info['version']['number']}!")
See hello.py for a working synchronous sample, and guides/ssl for how to setup SSL certificates.
index_name = 'test-index'
index_body = {
'settings': {
'index': {
'number_of_shards': 4
}
}
}
response = client.indices.create(
index_name,
body=index_body
)
print(response)
document = {
'title': 'Moneyball',
'director': 'Bennett Miller',
'year': '2011'
}
id = '1'
response = client.index(
index = index_name,
body = document,
id = id,
refresh = True
)
print(response)
q = 'miller'
query = {
'size': 5,
'query': {
'multi_match': {
'query': q,
'fields': ['title^2', 'director']
}
}
}
response = client.search(
body = query,
index = index_name
)
print(response)
response = client.delete(
index = index_name,
id = id
)
print(response)
response = client.indices.delete(
index = index_name
)
print(response)