Python client

The OpenSearch Python client provides a more natural syntax for interacting with your cluster. Rather than sending HTTP requests to a given URL, you can create an OpenSearch client for your cluster and call the client’s built-in functions.

Setup

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

  1. pip install opensearch-py

Then import it like any other module:

  1. from opensearchpy import OpenSearch

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

Sample code

  1. from opensearchpy import OpenSearch
  2. host = 'localhost'
  3. port = 9200
  4. auth = ('admin', 'admin') # For testing only. Don't store credentials in code.
  5. ca_certs_path = '/full/path/to/root-ca.pem' # Provide a CA bundle if you use intermediate CAs with your root CA.
  6. # Optional client certificates if you don't want to use HTTP basic authentication.
  7. # client_cert_path = '/full/path/to/client.pem'
  8. # client_key_path = '/full/path/to/client-key.pem'
  9. # Create the client with SSL/TLS enabled, but hostname verification disabled.
  10. client = OpenSearch(
  11. hosts = [{'host': host, 'port': port}],
  12. http_compress = True, # enables gzip compression for request bodies
  13. http_auth = auth,
  14. # client_cert = client_cert_path,
  15. # client_key = client_key_path,
  16. use_ssl = True,
  17. verify_certs = True,
  18. ssl_assert_hostname = False,
  19. ssl_show_warn = False,
  20. ca_certs = ca_certs_path
  21. )
  22. # Create an index with non-default settings.
  23. index_name = 'python-test-index'
  24. index_body = {
  25. 'settings': {
  26. 'index': {
  27. 'number_of_shards': 4
  28. }
  29. }
  30. }
  31. response = client.indices.create(index_name, body=index_body)
  32. print('\nCreating index:')
  33. print(response)
  34. # Add a document to the index.
  35. document = {
  36. 'title': 'Moneyball',
  37. 'director': 'Bennett Miller',
  38. 'year': '2011'
  39. }
  40. id = '1'
  41. response = client.index(
  42. index = index_name,
  43. body = document,
  44. id = id,
  45. refresh = True
  46. )
  47. print('\nAdding document:')
  48. print(response)
  49. # Search for the document.
  50. q = 'miller'
  51. query = {
  52. 'size': 5,
  53. 'query': {
  54. 'multi_match': {
  55. 'query': q,
  56. 'fields': ['title^2', 'director']
  57. }
  58. }
  59. }
  60. response = client.search(
  61. body = query,
  62. index = index_name
  63. )
  64. print('\nSearch results:')
  65. print(response)
  66. # Delete the document.
  67. response = client.delete(
  68. index = index_name,
  69. id = id
  70. )
  71. print('\nDeleting document:')
  72. print(response)
  73. # Delete the index.
  74. response = client.indices.delete(
  75. index = index_name
  76. )
  77. print('\nDeleting index:')
  78. print(response)