Files
opensearch-pyd/USER_GUIDE.md
T
Daniel (dB.) Doubrovkine f54973e583 Added k-nn user guide and samples. (#449)
* Added k-nn user guide and samples.

Signed-off-by: dblock <dblock@amazon.com>

* Added async samples.

Signed-off-by: dblock <dblock@amazon.com>

* Renamed Lucene Filters with Efficient Filters.

Signed-off-by: dblock <dblock@amazon.com>

* Fixing TOC from Lucene filters to Efficient filters

Signed-off-by: Vacha Shah <vachshah@amazon.com>

---------

Signed-off-by: dblock <dblock@amazon.com>
Signed-off-by: Vacha Shah <vachshah@amazon.com>
Co-authored-by: Vacha Shah <vachshah@amazon.com>
2023-07-25 19:04:13 -07:00

3.5 KiB

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