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.

    This getting started guide illustrates how to connect to OpenSearch, index documents, and run queries. For the client source code, see the opensearch-dsl-py repo.

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

    copy

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

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

    copy

    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. )

    copy

    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:

    copy

    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)

    copy

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

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

    copy

    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)

    copy

    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:

    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()

    copy

    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. }

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

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

    copy

    Deleting an index

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

    copy

    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 then 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. index_body = {
    18. 'settings': {
    19. 'index': {
    20. 'number_of_shards': 4
    21. }
    22. }
    23. }
    24. response = client.indices.create(index_name, index_body)
    25. print('\nCreating index:')
    26. print(response)
    27. # Create the structure of the document
    28. class Movie(Document):
    29. title = Text(fields={'raw': Keyword()})
    30. director = Text()
    31. year = Text()
    32. class Index:
    33. name = index_name
    34. def save(self, ** kwargs):
    35. return super(Movie, self).save(** kwargs)
    36. # Set up the opensearch-py version of the document
    37. Movie.init(using=client)
    38. doc = Movie(meta={'id': 1}, title='Moneyball', director='Bennett Miller', year='2011')
    39. response = doc.save(using=client)
    40. print('\nAdding document:')
    41. print(response)
    42. # Perform bulk operations
    43. 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"} }'
    44. client.bulk(movies)
    45. # Search for the document.
    46. s = Search(using=client, index=index_name) \
    47. .filter('term', year='2011') \
    48. .query('match', title='Moneyball')
    49. response = s.execute()
    50. print('\nSearch results:')
    51. for hit in response:
    52. print(hit.meta.score, hit.title)
    53. # Delete the document.
    54. print('\nDeleting document:')
    55. print(response)
    56. # Delete the index.
    57. response = client.indices.delete(
    58. index = index_name
    59. )
    60. print(response)

    copy