Skip to content

Latest commit

 

History

History
169 lines (130 loc) · 3.81 KB

USER_GUIDE.md

File metadata and controls

169 lines (130 loc) · 3.81 KB

OpenSearch Python Client User Guide

Setup

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.

Basic Features

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.

Creating a Client

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.

Creating an Index

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

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

print(response)

Adding a Document to an Index

document = {
  'title': 'Moneyball',
  'director': 'Bennett Miller',
  'year': '2011'
}

id = '1'

response = client.index(
    index = index_name,
    body = document,
    id = id,
    refresh = True
)

print(response)

Searching for a Document

q = 'miller'
query = {
  'size': 5,
  'query': {
    'multi_match': {
      'query': q,
      'fields': ['title^2', 'director']
    }
  }
}

response = client.search(
    body = query,
    index = index_name
)

print(response)

Deleting a Document

response = client.delete(
    index = index_name,
    id = id
)
print(response)

Deleting an Index

response = client.indices.delete(
    index = index_name
)

print(response)

Advanced Features

Plugins