High-level Python client

The OpenSearch high-level Python client (opensearch-dsl-py) provides wrapper classes for common OpenSearch entities, like documents, so you can work with them as Python objects. Additionally, the high-level client simplifies writing queries and supplies convenient Python methods for common OpenSearch operations. The high-level Python client supports creating and indexing documents, searching with and without filters, and updating documents using queries.

Setup

To add the client to your project, install it using pip:

  1. pip install opensearch-dsl

After installing the client, you can import it like any other module:

  1. from opensearchpy import OpenSearch
  2. from opensearch_dsl import Search

If you prefer to add the client manually or just want to examine the source code, see opensearch-dsl-py on GitHub.

Connecting to OpenSearch

To connect to the default OpenSearch host, create a client object with SSL enabled if you are using the Security plugin. You can use the default credentials for testing purposes:

  1. host = 'localhost'
  2. port = 9200
  3. auth = ('admin', 'admin') # For testing only. Don't store credentials in code.
  4. ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA.
  5. # Create the client with SSL/TLS enabled, but hostname verification disabled.
  6. client = OpenSearch(
  7. hosts = [{'host': host, 'port': port}],
  8. http_compress = True, # enables gzip compression for request bodies
  9. http_auth = auth,
  10. use_ssl = True,
  11. verify_certs = True,
  12. ssl_assert_hostname = False,
  13. ssl_show_warn = False,
  14. ca_certs = ca_certs_path
  15. )

If you have your own client certificates, specify them in the client_cert_path and client_key_path parameters:

  1. host = 'localhost'
  2. port = 9200
  3. auth = ('admin', 'admin') # For testing only. Don't store credentials in code.
  4. ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA.
  5. # Optional client certificates if you don't want to use HTTP basic authentication.
  6. client_cert_path = '/full/path/to/client.pem'
  7. client_key_path = '/full/path/to/client-key.pem'
  8. # Create the client with SSL/TLS enabled, but hostname verification disabled.
  9. client = OpenSearch(
  10. hosts = [{'host': host, 'port': port}],
  11. http_compress = True, # enables gzip compression for request bodies
  12. http_auth = auth,
  13. client_cert = client_cert_path,
  14. client_key = client_key_path,
  15. use_ssl = True,
  16. verify_certs = True,
  17. ssl_assert_hostname = False,
  18. ssl_show_warn = False,
  19. ca_certs = ca_certs_path
  20. )

If you are not using the Security plugin, create a client object with SSL disabled:

  1. host = 'localhost'
  2. port = 9200
  3. # Create the client with SSL/TLS and hostname verification disabled.
  4. client = OpenSearch(
  5. hosts = [{'host': host, 'port': port}],
  6. http_compress = True, # enables gzip compression for request bodies
  7. use_ssl = False,
  8. verify_certs = False,
  9. ssl_assert_hostname = False,
  10. ssl_show_warn = False
  11. )

Creating an index

To create an OpenSearch index, use the client.indices.create() method. You can use the following code to construct a JSON object with custom settings:

  1. index_name = 'my-dsl-index'
  2. index_body = {
  3. 'settings': {
  4. 'index': {
  5. 'number_of_shards': 4
  6. }
  7. }
  8. }
  9. response = client.indices.create(index_name, body=index_body)

Indexing a document

You can create a class to represent the documents that you’ll index in OpenSearch by extending the Document class:

  1. class Movie(Document):
  2. title = Text(fields={'raw': Keyword()})
  3. director = Text()
  4. year = Text()
  5. class Index:
  6. name = index_name
  7. def save(self, ** kwargs):
  8. return super(Movie, self).save(** kwargs)

To index a document, create an object of the new class and call its save() method:

  1. # Set up the opensearch-py version of the document
  2. Movie.init(using=client)
  3. doc = Movie(meta={'id': 1}, title='Moneyball', director='Bennett Miller', year='2011')
  4. response = doc.save(using=client)

Performing bulk operations

You can perform several operations at the same time by using the bulk() method of the client. The operations may be of the same type or of different types. Note that the operations must be separated by a \n and the entire string must be a single line:

  1. movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }'
  2. client.bulk(movies)

Searching for documents

You can use the Search class to construct a query. The following code creates a Boolean query with a filter:

  1. s = Search(using=client, index=index_name) \
  2. .filter("term", year="2011") \
  3. .query("match", title="Moneyball")
  4. response = s.execute()

The preceding query is equivalent to the following query in OpenSearch domain-specific language (DSL):

  1. GET my-dsl-index/_search
  2. {
  3. "query": {
  4. "bool": {
  5. "must": {
  6. "match": {
  7. "title": "Moneyball"
  8. }
  9. },
  10. "filter": {
  11. "term" : {
  12. "year": 2011
  13. }
  14. }
  15. }
  16. }
  17. }

Deleting a document

You can delete a document using the client.delete() method:

  1. response = client.delete(
  2. index = 'my-dsl-index',
  3. id = '1'
  4. )

Deleting an index

You can delete an index using the client.indices.delete() method:

  1. response = client.indices.delete(
  2. index = 'my-dsl-index'
  3. )

Sample program

The following sample program creates a client, adds an index with non-default settings, inserts a document, performs bulk operations, searches for the document, deletes the document, and, finally, deletes the index:

  1. from opensearchpy import OpenSearch
  2. from opensearch_dsl import Search, Document, Text, Keyword
  3. host = 'localhost'
  4. port = 9200
  5. auth = ('admin', 'admin') # For testing only. Don't store credentials in code.
  6. ca_certs_path = 'root-ca.pem'
  7. # Create the client with SSL/TLS enabled, but hostname verification disabled.
  8. client = OpenSearch(
  9. hosts=[{'host': host, 'port': port}],
  10. http_compress=True, # enables gzip compression for request bodies
  11. # http_auth=auth,
  12. use_ssl=False,
  13. verify_certs=False,
  14. ssl_assert_hostname=False,
  15. ssl_show_warn=False,
  16. # ca_certs=ca_certs_path
  17. )
  18. index_name = 'my-dsl-index'
  19. index_body = {
  20. 'settings': {
  21. 'index': {
  22. 'number_of_shards': 4
  23. }
  24. }
  25. }
  26. response = client.indices.create(index_name, index_body)
  27. print('\nCreating index:')
  28. print(response)
  29. # Create the structure of the document
  30. class Movie(Document):
  31. title = Text(fields={'raw': Keyword()})
  32. director = Text()
  33. year = Text()
  34. class Index:
  35. name = index_name
  36. def save(self, ** kwargs):
  37. return super(Movie, self).save(** kwargs)
  38. # Set up the opensearch-py version of the document
  39. Movie.init(using=client)
  40. doc = Movie(meta={'id': 1}, title='Moneyball', director='Bennett Miller', year='2011')
  41. response = doc.save(using=client)
  42. print('\nAdding document:')
  43. print(response)
  44. # Perform bulk operations
  45. movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }'
  46. client.bulk(movies)
  47. # Search for the document.
  48. s = Search(using=client, index=index_name) \
  49. .filter('term', year='2011') \
  50. .query('match', title='Moneyball')
  51. response = s.execute()
  52. print('\nSearch results:')
  53. for hit in response:
  54. print(hit.meta.score, hit.title)
  55. # Delete the document.
  56. print('\nDeleting document:')
  57. print(response)
  58. # Delete the index.
  59. response = client.indices.delete(
  60. index = index_name
  61. )
  62. print('\nDeleting index:')
  63. print(response)