How To Use OpenSearch in Python

A guide on how to index and search data with OpenSearch from your Python app.

Need to add search functionality to your Python app? This guide walks you through everything you need to get started with OpenSearch, from setting up your first index to writing fuzzy and multi-field queries.

Getting Started

First, install the opensearch-py library:

pip install opensearch-py

Connecting to OpenSearch

Establish a connection to your OpenSearch instance using the following code:

from opensearchpy import OpenSearch

client = OpenSearch(
    hosts = [{'host': 'localhost', 'port': 9200}],
    http_compress = True,
    use_ssl = False,
    verify_certs = False,
)

Creating an Index

Initialize a new index with specific settings for number of shards and replicas.

index_name = 'my-index'
index_body = {
  'settings': {
    'index': {
      'number_of_shards': 4
    }
  }
}

response = client.indices.create(index_name, body=index_body)
print(response)