### GET Request Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client/http.html Performs a GET request to the specified URL. ```APIDOC ## GET / ### Description Performs a GET request to the specified URL. ### Method GET ### Endpoint / ### Parameters #### Path Parameters - **url** (str) - Required - The absolute URL (without host) to target. #### Query Parameters - **params** (Mapping[str, Any]) - Optional - Dictionary of query parameters. #### Headers - **headers** (Mapping[str, Any]) - Optional - Dictionary of headers. #### Request Body - **body** (Any) - Optional - The body of the request, will be serialized. ### Response #### Success Response (200) - **data** (Any) - The data returned from the request. ``` -------------------------------- ### Initialize OpenSearch Client Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client.html Demonstrates initializing the OpenSearch client with a list of hosts. Supports various host formats including dictionaries and URL strings with authentication. ```python from opensearchpy import OpenSearch client = OpenSearch( hosts=[ 'http://user:secret@localhost:9200/', 'https://user:secret@other_host:443/production' ], verify_certs=True ) ``` -------------------------------- ### DummyConnectionPool.__init__ Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/connection_pool.html Initializes the DummyConnectionPool with a single connection. ```APIDOC ## DummyConnectionPool.__init__ ### Description Initializes the DummyConnectionPool. Requires exactly one connection to be defined. ### Method `__init__(connections: Any, **kwargs: Any)` ### Parameters - **connections** (Any) - A list or tuple containing connection details. - **kwargs** (Any) - Additional keyword arguments. ``` -------------------------------- ### get Source: https://opensearch-project.github.io/opensearch-py/api-ref/helpers/index.html The get index API allows to retrieve information about the index. Any additional keyword arguments will be passed to `OpenSearch.indices.get` unchanged. ```APIDOC ## get ### Description The get index API allows to retrieve information about the index. ### Parameters - **using** (_OpenSearch_ | _None_) - **kwargs** (_Any_) ### Return type _Any_ ``` -------------------------------- ### Get Snapshot Status Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/snapshot_client.html Retrieves information about the status of a snapshot. You can specify the repository and snapshot name to get details about a specific snapshot. ```APIDOC ## GET /_snapshot/{repository}/{snapshot}/_status ### Description Returns information about the status of a snapshot. ### Method GET ### Endpoint /_snapshot/{repository}/{snapshot}/_status ### Parameters #### Query Parameters - **repository** (Any) - Required - The name of the repository containing the snapshot. - **snapshot** (Any) - Optional - A comma-separated list of snapshot names. - **cluster_manager_timeout** (Time) - Optional - The amount of time to wait for a response from the cluster manager node. - **error_trace** (Boolean) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (String) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field’s name. To exclude fields, use -. - **human** (Boolean) - Optional - Whether to return human-readable values for statistics. Default is false. - **ignore_unavailable** (Boolean) - Optional - Whether to ignore any unavailable snapshots. When false, a SnapshotMissingException is thrown. Default is false. - **pretty** (Boolean) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (String) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ### Response #### Success Response (200) - **response** (Any) - Description of the response body. ``` -------------------------------- ### Client Initialization with RFC-1738 URLs Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/opensearch_client.html Initialize the client using RFC-1738 formatted URLs, which can include authentication credentials and URL prefixes. ```python client = OpenSearch( [ 'http://user:secret@localhost:9200/', 'https://user:secret@other_host:443/production' ], verify_certs=True ) ``` -------------------------------- ### Initialize Index and Mappings Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/helpers/document.html Use the `init` class method to create the OpenSearch index and populate it with the defined mappings. You can specify a custom index name or use the default one associated with the document class. ```python Document.init(index='my-custom-index') # or # MyDocument.init() ``` -------------------------------- ### Get All Users (Legacy) - Python Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client/security.html Retrieves all internal users via the legacy API. This method does not require any specific user parameters. Use this to get a list of all configured users. ```python return self.transport.perform_request( "GET", "/_plugins/_security/api/user", params=params, headers=headers ) ``` -------------------------------- ### OpenSearch Client Initialization Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client.html Demonstrates how to initialize the OpenSearch client with various configuration options, including hosts, transport class, and custom serializers. ```APIDOC ## OpenSearch Client Initialization ### Description Initialize the OpenSearch client with a list of hosts, a custom transport class, or other keyword arguments that will be passed to the transport and connection classes. You can also provide a custom serializer. ### Parameters * **hosts** (list or str): A list of node dictionaries or connection strings, or a single node. Defaults to `None`. * **transport_class** (Type[Transport]): The transport class to use. Defaults to `Transport`. * ****kwargs**: Additional arguments passed to `Transport` and `Connection`. ### Example ```python from opensearchpy import OpenSearch # With default settings client = OpenSearch( hosts=[ 'localhost:9200', {'host': 'other_host', 'port': 9200} ], http_auth=('user', 'secret'), use_ssl=True, verify_certs=True, ssl_assert_hostname=False, ssl_show_warn=False, ) # With custom serializer from opensearchpy.serializer import JSONSerializer class SetEncoder(JSONSerializer): def default(self, obj): if isinstance(obj, set): return list(obj) return JSONSerializer.default(self, obj) client = OpenSearch(serializer=SetEncoder()) ``` ``` -------------------------------- ### HTTP GET Request Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client/http.html Perform a GET request to a specified URL. Pass headers, query parameters, and a request body if needed. The underlying transport layer handles serialization and execution. ```python def get( self, url: str, headers: Optional[Mapping[str, Any]] = None, params: Optional[Mapping[str, Any]] = None, body: Any = None, ) -> Any: """ Perform a GET request and return the data. :arg url: absolute url (without host) to target :arg headers: dictionary of headers, will be handed over to the underlying :class:`~opensearchpy.Connection` class :arg params: dictionary of query parameters, will be handed over to the underlying :class:`~opensearchpy.Connection` class for serialization :arg body: body of the request, will be serialized using serializer and passed to the connection """ return self.transport.perform_request( "GET", url=url, headers=headers, params=params, body=body ) ``` -------------------------------- ### OpenSearch Client Initialization Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/opensearch_client.html Demonstrates different ways to initialize the OpenSearch client, including basic node configuration, SSL/TLS settings, and custom serializers. ```APIDOC ## Basic Initialization ### Description Instantiate the client with a list of host dictionaries. ### Code ```python from opensearchpy import OpenSearch client = OpenSearch([ {'host': 'localhost'}, {'host': 'othernode', 'port': 443, 'url_prefix': 'opensearch', 'use_ssl': True}, ]) ``` ## SSL/TLS Configuration ### Description Configure SSL/TLS for secure connections, including certificate verification and client authentication. ### Code ```python # With certificate verification client = OpenSearch( ['localhost:443', 'other_host:443'], use_ssl=True, verify_certs=True, ca_certs='/path/to/CA_certs' ) # Without certificate verification (with warnings disabled) client = OpenSearch( ['localhost:443', 'other_host:443'], use_ssl=True, verify_certs=False, ssl_assert_hostname=False, ssl_show_warn=False ) # With client certificate authentication client = OpenSearch( ['localhost:443', 'other_host:443'], use_ssl=True, verify_certs=True, ca_certs='/path/to/CA_certs', client_cert='/path/to/clientcert.pem', client_key='/path/to/clientkey.pem' ) ``` ## RFC-1738 URL Format ### Description Initialize the client using RFC-1738 formatted URLs. ### Code ```python client = OpenSearch([ 'http://user:secret@localhost:9200/', 'https://user:secret@other_host:443/production' ], verify_certs=True ) ``` ## Custom Serializer ### Description Implement and use a custom serializer for encoding outgoing requests. ### Code ```python from opensearchpy.serializer import JSONSerializer class SetEncoder(JSONSerializer): def default(self, obj): if isinstance(obj, set): return list(obj) if isinstance(obj, Something): return 'CustomSomethingRepresentation' return JSONSerializer.default(self, obj) client = OpenSearch(serializer=SetEncoder()) ``` ``` -------------------------------- ### get_message Source: https://opensearch-project.github.io/opensearch-py/api-ref/plugins/ml_plugin.html Get a message. ```APIDOC ## GET /_plugins/_ml/chat/messages/{message_id} ### Description Get a message. ### Method GET ### Endpoint /_plugins/_ml/chat/messages/{message_id} ### Parameters #### Query Parameters - **error_trace** (boolean) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (string) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field’s name. To exclude fields, use -. - **human** (boolean) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (boolean) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (string) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ### Response #### Success Response (200) - **message** (object) - Description of the message object. #### Response Example ```json { "message": { "id": "example_message_id", "content": "example message content" } } ``` ``` -------------------------------- ### get_memory Source: https://opensearch-project.github.io/opensearch-py/api-ref/plugins/ml_plugin.html Get a memory. ```APIDOC ## GET /_plugins/_ml/memory/{memory_id} ### Description Get a memory. ### Method GET ### Endpoint /_plugins/_ml/memory/{memory_id} ### Parameters #### Query Parameters - **error_trace** (boolean) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (string) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field’s name. To exclude fields, use -. - **human** (boolean) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (boolean) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (string) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ### Response #### Success Response (200) - **memory** (object) - Description of the memory object. #### Response Example ```json { "memory": { "id": "example_memory_id", "content": "example content" } } ``` ``` -------------------------------- ### Security Client Initialization Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/security_client.html Initialize the Security Client with an existing OpenSearch client instance. ```APIDOC from opensearchpy import OpenSearch from opensearchpy.client import security # Assuming 'client' is an initialized OpenSearch client instance # client = OpenSearch(...) security_client = security.SecurityClient(client) ``` -------------------------------- ### Connection with Different Host Configurations Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/opensearch_client.html Demonstrates connecting to different hosts, where each host can have specific parameters, such as using SSL on a particular port. ```APIDOC ## Connection with Different Host Configurations ### Description Connect to localhost directly and another node using SSL on port 443. Different hosts can have different parameters, use a dictionary per node to specify those. ### Method Instantiate `OpenSearch` client with a list of host dictionaries, each specifying connection parameters. ### Endpoint N/A (Client-side configuration) ### Request Example ```python from opensearchpy import OpenSearch client = OpenSearch( [ {'host': 'localhost', 'port': 9200}, {'host': 'opensearchnode1', 'port': 443, 'use_ssl': True, 'verify_certs': True, 'ssl_assert_hostname': False, 'ssl_show_warn': False} ] ) ``` ### Response N/A (Client-side configuration) ``` -------------------------------- ### get_message_traces Source: https://opensearch-project.github.io/opensearch-py/api-ref/plugins/ml_plugin.html Get a message traces. ```APIDOC ## GET /_plugins/_ml/chat/traces/{message_id} ### Description Get a message traces. ### Method GET ### Endpoint /_plugins/_ml/chat/traces/{message_id} ### Parameters #### Query Parameters - **error_trace** (boolean) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (string) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field’s name. To exclude fields, use -. - **human** (boolean) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (boolean) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (string) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ### Response #### Success Response (200) - **traces** (array) - An array of message trace objects. #### Response Example ```json { "traces": [ { "timestamp": "2023-01-01T10:00:00Z", "event": "processing" } ] } ``` ``` -------------------------------- ### get_memory_container Source: https://opensearch-project.github.io/opensearch-py/api-ref/plugins/ml_plugin.html Get a memory container. ```APIDOC ## GET /_plugins/_ml/memory/containers/{memory_container_id} ### Description Get a memory container. ### Method GET ### Endpoint /_plugins/_ml/memory/containers/{memory_container_id} ### Parameters #### Query Parameters - **error_trace** (boolean) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (string) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field’s name. To exclude fields, use -. - **human** (boolean) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (boolean) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (string) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ### Response #### Success Response (200) - **memory_container** (object) - Description of the memory container object. #### Response Example ```json { "memory_container": { "id": "example_container_id", "name": "example_container" } } ``` ``` -------------------------------- ### Configure OpenSearch Client with Different Host Parameters Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/opensearch_client.html Connect to different hosts with specific parameters, using a dictionary for each node to define individual configurations. ```python # connect to localhost directly and another node using SSL on port 443 ``` -------------------------------- ### Get Alerts Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/alerting.html Retrieves all alerts. ```APIDOC ## GET _plugins/_alerting/monitors/alerts ### Description Returns all alerts. ### Method GET ### Endpoint _plugins/_alerting/monitors/alerts ``` -------------------------------- ### Configure OpenSearch Client with SSL Client Authentication Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client.html Set up SSL client authentication by providing paths to the client certificate and private key, along with CA certificates for verification. ```python client = OpenSearch( ['localhost:443', 'other_host:443'], # turn on SSL use_ssl=True, # make sure we verify SSL certificates verify_certs=True, # provide a path to CA certs on disk ca_certs='/path/to/CA_certs', # PEM formatted SSL client certificate client_cert='/path/to/clientcert.pem', # PEM formatted SSL client key client_key='/path/to/clientkey.pem' ) ``` -------------------------------- ### create_tenant Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/security_client.html Creates or replaces the specified tenant. ```APIDOC ## create_tenant ### Description Creates or replaces the specified tenant. ### Method POST ### Endpoint /_plugins/_security/tenants/{tenant} ### Parameters #### Path Parameters - **tenant** (Any) - Required - The name of the tenant to create. #### Query Parameters - **error_trace** (Boolean) - Optional - Whether to include the stack trace of returned errors. - **filter_path** (String) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field’s name. To exclude fields, use -. - **human** (Boolean) - Optional - Whether to return human-readable values for statistics. - **pretty** (Boolean) - Optional - Whether to pretty-format the returned JSON response. - **source** (String) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. #### Request Body - **body** (Any) - Required - The tenant definition. - **params** (Any) - Optional - Additional parameters. - **headers** (Any) - Optional - Additional headers. ``` -------------------------------- ### Metrics Class Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/metrics/metrics.html The Metrics class is an abstract base class that defines the interface for managing request metrics. It includes methods for starting and ending requests, and properties to access the start time, end time, and service time. ```APIDOC ## Class Metrics ### Description The Metrics class defines methods and properties for managing request metrics, including start time, end time, and service time, serving as a blueprint for concrete implementations. ### Methods - **request_start()**: Abstract method to mark the beginning of a request. - **request_end()**: Abstract method to mark the end of a request. ### Properties - **start_time**: Abstract property to get the request start time. Returns Optional[float]. - **end_time**: Abstract property to get the request end time. Returns Optional[float]. - **service_time**: Abstract property to calculate and get the service time. Returns Optional[float]. ``` -------------------------------- ### Get Message Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/ml.html Retrieves a message by its ID. ```APIDOC ## GET _plugins/_ml/messages/{message_id} ### Description Get a message. ### Method GET ### Endpoint _plugins/_ml/messages/{message_id} ### Parameters #### Path Parameters - **message_id** (Any) - Required - The ID of the message to retrieve. #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ``` -------------------------------- ### EmptyConnectionPool.__init__ Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/connection_pool.html Initializes an empty connection pool. ```APIDOC ## EmptyConnectionPool.__init__ ### Description Initializes an empty connection pool. Errors out if used. ### Method `__init__(*_: Any, **__: Any)` ### Parameters None ``` -------------------------------- ### Get Memory Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/ml.html Retrieves a memory by its ID. ```APIDOC ## GET _plugins/_ml/memory/{memory_id} ### Description Get a memory. ### Method GET ### Endpoint _plugins/_ml/memory/{memory_id} ### Parameters #### Path Parameters - **memory_id** (Any) - Required - The ID of the memory to retrieve. #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ``` -------------------------------- ### Create Tenant Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client/security.html Creates a new tenant with the specified name and configuration. ```APIDOC ## PUT _plugins/_security/api/tenants/{tenant} ### Description Adds, deletes, or modifies a single tenant. ### Method PUT ### Endpoint /_plugins/_security/api/tenants/{tenant} ### Parameters #### Path Parameters - **tenant** (Any) - Required - The name of the tenant to create. #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. #### Request Body - **body** (Any) - Required - The configuration for the tenant. ### Response #### Success Response (200) - **field1** (type) - Description ``` -------------------------------- ### create Source: https://opensearch-project.github.io/opensearch-py/api-ref/clients/snapshot_client.html Creates a snapshot within an existing repository. ```APIDOC ## create ### Description Creates a snapshot within an existing repository. ### Method PUT ### Endpoint /_snapshot// ### Parameters #### Path Parameters - **repository** (Any) - Required - The name of the repository where the snapshot will be stored. - **snapshot** (Any) - Required - The name of the snapshot. Must be unique in the repository. #### Query Parameters - **cluster_manager_timeout** (Any) - Optional - The amount of time to wait for a response from the cluster manager node. For more information about supported time units, see [Common parameters](https://opensearch.org/docs/latest/api-reference/common-parameters/#time-units). - **error_trace** (Boolean) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field’s name. To exclude fields, use -. - **human** (Boolean) - Optional - Whether to return human-readable values for statistics. Default is false. - **master_timeout** (Any) - Deprecated - To promote inclusive language, use cluster_manager_timeout instead. Period to wait for a connection to the cluster-manager node. If no response is received before the timeout expires, the request fails and returns an error. - **pretty** (Boolean) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. - **wait_for_completion** (Boolean) - Optional - When true, the request returns a response when the snapshot is complete. When false, the request returns a response when the snapshot initializes. Default is false. #### Request Body - **body** (Any) - Optional - The snapshot definition. ### Request Example ```json { "example": "request body for create" } ``` ### Response #### Success Response (200) - **response** (Any) - Description of the response body. #### Response Example ```json { "example": "response body for create" } ``` ``` -------------------------------- ### Get All Roles Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client/security.html Retrieves all available roles. ```APIDOC ## GET _plugins/_security/api/roles ### Description Retrieves all roles. ### Method GET ### Endpoint /_plugins/_security/api/roles ### Parameters #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ### Response #### Success Response (200) - **field1** (Any) - Description ``` -------------------------------- ### FacetedSearch Example Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/helpers/faceted_search.html Demonstrates how to define and use a FacetedSearch class for blog posts. It includes setting the index, document types, fields, and defining various facets like terms and date histograms. It also shows how to override the search method to add custom filters and how to execute the search and access results. ```python class BlogSearch(FacetedSearch): index = 'blogs' doc_types = [Blog, Post] fields = ['title^5', 'category', 'description', 'body'] facets = { 'type': TermsFacet(field='_type'), 'category': TermsFacet(field='category'), 'weekly_posts': DateHistogramFacet(field='published_from', interval='week') } def search(self): ' Override search to add your own filters ' s = super(BlogSearch, self).search() return s.filter('term', published=True) # when using: blog_search = BlogSearch("web framework", filters={"category": "python"}) # supports pagination blog_search[10:20] response = blog_search.execute() # easy access to aggregation results: for category, hit_count, is_selected in response.facets.category: print( "Category %s has %d hits%s." % ( category, hit_count, ' and is chosen' if is_selected else '' ) ) ``` -------------------------------- ### explain_index Source: https://opensearch-project.github.io/opensearch-py/api-ref/plugins/index_management_plugin.html Gets the current state of the index. ```APIDOC ## explain_index ### Description Gets the current state of the index. ### Method GET ### Endpoint /_plugins/_ism/explain/{index} ### Parameters #### Path Parameters * **index** (Any) - Required - The name of the index to explain #### Query Parameters * **params** (Any) - Optional - Additional query parameters * **headers** (Any) - Optional - Additional headers ### Response #### Success Response (200) * **response** (Any) - The state of the index. ``` -------------------------------- ### Connection Class Initialization Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/connection/base.html Initializes a new Connection instance with various configuration options for connecting to an OpenSearch node. ```APIDOC ## Connection ### Description Class responsible for maintaining a connection to an OpenSearch node. It holds persistent connection pool to it and its main interface (`perform_request`) is thread-safe. Also responsible for logging. ### Parameters - **host** (str) - hostname of the node (default: localhost) - **port** (Optional[int]) - port to use (integer, default: 9200) - **use_ssl** (bool) - use ssl for the connection if `True` - **url_prefix** (str) - optional url prefix for opensearch - **timeout** (int) - default timeout in seconds (float, default: 10) - **headers** (Optional[Dict[str, str]]) - custom headers to send with requests - **http_compress** (Optional[bool]) - Use gzip compression - **opaque_id** (Optional[str]) - Send this value in the 'X-Opaque-Id' HTTP header for tracing all requests made by this transport. - **kwargs** (Any) - Additional keyword arguments. ``` -------------------------------- ### Get Profile Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/ml.html Retrieves the ML profile information. ```APIDOC ## GET _plugins/_ml/profile ### Description Retrieves the ML profile information. ### Method GET ### Endpoint /_plugins/_ml/profile ### Parameters #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. #### Request Body - **body** (Any) - Optional - The request body for the profile query. ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example { "example": "response body" } ``` -------------------------------- ### Get Model Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/ml.html Retrieves a specific ML model. ```APIDOC ## GET _plugins/_ml/models/{model_id} ### Description Retrieves a specific ML model. ### Method GET ### Endpoint _plugins/_ml/models/{model_id} ### Parameters #### Path Parameters - **model_id** (Any) - Required - The ID of the model to retrieve. #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example { "example": "response body" } ``` -------------------------------- ### Async HTTP Client Initialization Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/_async/http_aiohttp.html Initializes the asynchronous HTTP client with various configuration options including SSL/TLS settings, connection pooling, and authentication. It handles SSL context creation and validation, client certificate loading, and sets default headers. ```python def __init__( self, host: str, port: int, http_auth: Optional[Tuple[str, str]] = None, use_ssl: bool = False, verify_certs: bool = VERIFY_CERTS_DEFAULT, ssl_assert_hostname: Optional[str] = None, ssl_assert_fingerprint: Optional[str] = None, ca_certs: Optional[str] = None, client_cert: Optional[str] = None, client_key: Optional[str] = None, ssl_context: Optional[ssl.SSLContext] = None, ssl_show_warn: bool = SSL_SHOW_WARN_DEFAULT, loop: Optional[asyncio.AbstractEventLoop] = None, timeout: Union[int, float] = DEFAULT_HTTP_TIMEOUT, session_class: Type[aiohttp.ClientSession] = aiohttp.ClientSession, **kwargs: Any, ) -> None: """Initialize the aiohttp client. :param host: Host to connect to. :param port: Port to connect to. :param http_auth: Tuple of (username, password) for Basic Auth. :param use_ssl: Whether to use SSL/TLS. :param verify_certs: Whether to verify SSL certificates. :param ssl_assert_hostname: Assert that the server hostname matches this value. :param ssl_assert_fingerprint: Assert that the server certificate fingerprint matches this value. :param ca_certs: Path to the CA certificates file. :param client_cert: Path to the client certificate file. :param client_key: Path to the client private key file. :param ssl_context: An existing SSLContext to use. :param ssl_show_warn: Whether to show SSL warnings. :param loop: The asyncio event loop to use. :param timeout: The HTTP request timeout in seconds. :param session_class: The aiohttp.ClientSession class to use. :param kwargs: Additional keyword arguments to pass to aiohttp.ClientSession. """ self.host = host self.port = port self.timeout = timeout self.scheme = "https" if use_ssl else "http" self.url_prefix = "" self.session_class = session_class self.headers = { "Accept": "application/json", "Content-Type": "application/json", } # If `ssl_context` is provided, it takes precedence over other SSL-related arguments. if ssl_context is not None and ( client_cert or client_key or ssl_version or verify_certs or ssl_assert_hostname or ssl_assert_fingerprint or ca_certs or ssl_show_warn ): warnings.warn( "When using `ssl_context`, all other SSL related kwargs are ignored" ) self.ssl_assert_fingerprint = ssl_assert_fingerprint if self.use_ssl and ssl_context is None: if ssl_version is None: ssl_context = ssl.create_default_context() else: ssl_context = ssl.SSLContext(ssl_version) # Convert all sentinel values to their actual default # values if not using an SSLContext. if verify_certs is VERIFY_CERTS_DEFAULT: verify_certs = True if ssl_show_warn is SSL_SHOW_WARN_DEFAULT: ssl_show_warn = True if verify_certs: ssl_context.verify_mode = ssl.CERT_REQUIRED ssl_context.check_hostname = ssl_assert_hostname else: ssl_context.check_hostname = False ssl_context.verify_mode = ssl.CERT_NONE if ca_certs is None: ca_certs = self.default_ca_certs() if verify_certs: if not ca_certs: raise ImproperlyConfigured( "Root certificates are missing for certificate " "validation. Either pass them in using the ca_certs parameter or " "install certifi to use it automatically." ) if os.path.isfile(ca_certs): ssl_context.load_verify_locations(cafile=ca_certs) elif os.path.isdir(ca_certs): ssl_context.load_verify_locations(capath=ca_certs) else: raise ImproperlyConfigured("ca_certs parameter is not a path") else: if ssl_show_warn: warnings.warn( "Connecting to %s using SSL with verify_certs=False is insecure." % self.host ) # Use client_cert and client_key variables for SSL certificate configuration. if client_cert and not os.path.isfile(client_cert): raise ImproperlyConfigured("client_cert is not a path to a file") if client_key and not os.path.isfile(client_key): raise ImproperlyConfigured("client_key is not a path to a file") if client_cert and client_key: ssl_context.load_cert_chain(client_cert, client_key) elif client_cert: ssl_context.load_cert_chain(client_cert) self.headers.setdefault("connection", "keep-alive") self.loop = loop self.session = None # Align with Sync Interface if "pool_maxsize" in kwargs: maxsize = kwargs.pop("pool_maxsize") # Parameters for creating an aiohttp.ClientSession later. self._limit = maxsize self._http_auth = http_auth self._ssl_context = ssl_context self._trust_env = trust_env ``` -------------------------------- ### Get Controller Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/ml.html Retrieves a controller by its model ID. ```APIDOC ## GET _plugins/_ml/controllers/{model_id} ### Description Retrieves a controller. ### Method GET ### Endpoint _plugins/_ml/controllers/{model_id} ### Parameters #### Path Parameters - **model_id** (Any) - Required - The ID of the model for which to retrieve the controller. #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ``` -------------------------------- ### ConnectionPool Initialization Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/connection_pool.html Initializes the ConnectionPool with a list of connections and configuration options. Raises an error if no connections are provided. ```python class ConnectionPool: connections_opts: Sequence[Tuple[Connection, Any]] connections: Any orig_connections: Tuple[Connection, ...] dead: Any dead_count: Dict[Any, int] dead_timeout: float timeout_cutoff: int selector: Any def __init__( self, connections: Any, dead_timeout: float = 60, timeout_cutoff: int = 5, selector_class: Type[ConnectionSelector] = RoundRobinSelector, randomize_hosts: bool = True, **kwargs: Any, ) -> None: """ :arg connections: list of tuples containing the :class:`~opensearchpy.Connection` instance and its options :arg dead_timeout: number of seconds a connection should be retired for after a failure, increases on consecutive failures :arg timeout_cutoff: number of consecutive failures after which the timeout doesn't increase :arg selector_class: :class:`~opensearchpy.ConnectionSelector` subclass to use if more than one connection is live :arg randomize_hosts: shuffle the list of connections upon arrival to avoid dog piling effect across processes """ if not connections: raise ImproperlyConfigured( "No defined connections, you need to " "specify at least one host." ) self.connection_opts = connections self.connections = [c for (c, opts) in connections] ``` -------------------------------- ### Get Connector Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/ml.html Retrieves a standalone connector by its ID. ```APIDOC ## GET _plugins/_ml/connectors/{connector_id} ### Description Retrieves a standalone connector. ### Method GET ### Endpoint _plugins/_ml/connectors/{connector_id} ### Parameters #### Path Parameters - **connector_id** (Any) - Required - The ID of the connector to retrieve. #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ``` -------------------------------- ### Create Snapshot - opensearch-py Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client/snapshot.html Use this method to create a snapshot within an existing repository. Specify the repository name, snapshot name, and optionally provide a snapshot definition in the body. The `wait_for_completion` parameter controls whether the response is returned upon initialization or completion of the snapshot. ```python from typing import Any from .utils import SKIP_IN_PATH, NamespacedClient, _make_path, query_params [docs] class SnapshotClient(NamespacedClient): [docs] @query_params( "cluster_manager_timeout", "error_trace", "filter_path", "human", "master_timeout", "pretty", "source", "wait_for_completion", ) def create( self, *, repository: Any, snapshot: Any, body: Any = None, params: Any = None, headers: Any = None, ) -> Any: """ Creates a snapshot within an existing repository. :arg repository: The name of the repository where the snapshot will be stored. :arg snapshot: The name of the snapshot. Must be unique in the repository. :arg body: The snapshot definition. :arg cluster_manager_timeout: The amount of time to wait for a response from the cluster manager node. For more information about supported time units, see [Common parameters](https://opensearch.org/docs/latest/api-reference/common- parameters/#time-units). :arg error_trace: Whether to include the stack trace of returned errors. Default is false. :arg filter_path: A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. :arg human: Whether to return human-readable values for statistics. Default is false. :arg master_timeout (Deprecated: To promote inclusive language, use `cluster_manager_timeout` instead.): Period to wait for a connection to the cluster-manager node. If no response is received before the timeout expires, the request fails and returns an error. :arg pretty: Whether to pretty-format the returned JSON response. Default is false. :arg source: The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. :arg wait_for_completion: When `true`, the request returns a response when the snapshot is complete. When `false`, the request returns a response when the snapshot initializes. Default is false. """ for param in (repository, snapshot): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_snapshot", repository, snapshot), params=params, headers=headers, body=body, ) ``` -------------------------------- ### OpenSearch Async Client Initialization Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/_async/client.html Initializes the asynchronous OpenSearch client with a list of hosts and optional transport class. Custom serializers can also be provided. ```APIDOC ## OpenSearch Async Client Initialization ### Description Initializes the asynchronous OpenSearch client with a list of hosts and optional transport class. Custom serializers can also be provided. ### Parameters - **hosts** (list or str) - A list of node dictionaries or connection strings, or a single node. Defaults to connection class defaults if not provided. - **transport_class** (Type[AsyncTransport]) - The transport class to use. Defaults to `AsyncTransport`. - **kwargs** (Any) - Additional arguments passed to `Transport` and `Connection`. ### Example ```python from opensearchpy import OpenSearch # Connect to OpenSearch client = OpenSearch( hosts=[ 'https://localhost:9200', 'https://user:secret@other_host:443/production' ], http_auth=('user', 'secret'), use_ssl=True, verify_certs=True, ssl_assert_hostname=False, ssl_show_warn=False, ) # Using a custom serializer from opensearchpy.serializer import JSONSerializer class SetEncoder(JSONSerializer): def default(self, obj): if isinstance(obj, set): return list(obj) return JSONSerializer.default(self, obj) client = OpenSearch(serializer=SetEncoder()) ``` ``` -------------------------------- ### Get All Tools Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/plugins/ml.html Retrieves a list of available tools. ```APIDOC ## GET _plugins/_ml/tools ### Description Retrieves tools. ### Method GET ### Endpoint /_plugins/_ml/tools ### Parameters #### Query Parameters - **error_trace** (Any) - Optional - Whether to include the stack trace of returned errors. Default is false. - **filter_path** (Any) - Optional - A comma-separated list of filters used to filter the response. Use wildcards to match any field or part of a field's name. To exclude fields, use `-`. - **human** (Any) - Optional - Whether to return human-readable values for statistics. Default is false. - **pretty** (Any) - Optional - Whether to pretty-format the returned JSON response. Default is false. - **source** (Any) - Optional - The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests. ``` -------------------------------- ### Configure OpenSearch Client with Different Host Parameters Source: https://opensearch-project.github.io/opensearch-py/_modules/opensearchpy/client.html Connect to multiple OpenSearch nodes, specifying individual parameters like port, url_prefix, and use_ssl for each host using a dictionary. ```python client = OpenSearch([ {'host': 'localhost'}, {'host': 'othernode', 'port': 443, 'url_prefix': 'opensearch', 'use_ssl': True}, ]) ```