Elasticsearch Python Client

repository·main·Indexed 26 days ago

https://github.com/elastic/elasticsearch-py

The official Python client for Elasticsearch, providing a high-level API to interact with Elasticsearch clusters. It includes support for JSON translation, automatic node discovery, load balancing, and asynchronous operations via AsyncElasticsearch.

Tokens
687.9K
Snippets
2.5K
Records
2.7K
Agent score
88%

What's inside elasticsearch-py

  1. Overview of Elasticsearch Python client modules

    main

    The Elasticsearch Python client package is composed of several specialized modules:

    • Core Client: The low-level client that provides access to the entire Elasticsearch API surface. It handles JSON translation, node discovery, load balancing, and persistent connections.
    • Bulk Helpers: High-level functions designed to simplify ingesting large volumes of data using Python iterables.
    • ES|QL Query Builder: An idiomatic interface for constructing ES|QL queries using Python expressions.
    • DSL Module: A high-level client that allows manipulating documents and queries using Python classes and objects instead of primitive types like dictionaries and lists.
  2. Use the ES|QL Query Builder

    main
    The elasticsearch.esql module provides a programmatic Query Builder for ES|QL (Elasticsearch Query Language). It allows you to construct complex ES|QL queries using a fluent Python API instead of raw strings. The builder is centered around the ESQL class and various command classes that represent ES|QL operations.
  3. Use the Domain Specific Language (DSL) for Elasticsearch operations

    main
    The elasticsearch.dsl module provides high-level abstractions for building Elasticsearch queries and managing resources using a Pythonic Domain Specific Language (DSL). Instead of constructing raw JSON dictionaries, you can use specialized classes to build complex search requests, manage indices, and handle document operations.
  4. Serialization best practices for Python DSL

    main

    When using the dsl module, it is highly recommended to use the built-in serializer (elasticsearch.dsl.serializer.serializer). This ensures objects are correctly converted to JSON.

    • create_connection and configure use this serializer automatically.
    • To support custom objects, define a to_dict() method on your objects; the serializer will call this method automatically during JSON conversion.
  5. Create ES|QL expressions using the E() helper

    main

    You can create ES|QL expressions in two ways:

    1. String-based: Provide the expression as a raw string (e.g., .eval(height_feet="height * 3.281")).
    2. Python-based: Use the E() helper function to wrap column names. This allows you to use Python operators which are automatically translated to ES|QL.

    Example of Python-based expression:

    from elasticsearch.esql import ESQL, E
    
    query = ESQL.from_("employees").eval(height_feet=E("height") * 3.281)
    from elasticsearch.esql import ESQL, E
    
    query = (
        ESQL.from_("employees")
        .sort("emp_no")
        .keep("first_name", "last_name", "height")
        .eval(height_feet=E("height") * 3.281, height_cm=E("height") * 100)
    )
  6. Use async variants of Elasticsearch helpers

    main
    The elasticsearch.helpers module provides asynchronous versions of all standard helpers. These async variants are prefixed with async_ (e.g., async_bulk, async_scan). Their API signatures are identical to their synchronous counterparts. If a helper accepts an iterator or generator, the async version also supports async iterators and async generators.
  7. Configure a default connection for Python DSL

    main

    To avoid explicitly passing a connection to every API call, you can define a global default connection using the create_connection method. This is the recommended approach for most applications. Any subsequent DSL operations will automatically use this connection.

    # Standard Python
    from elasticsearch.dsl import connections
    connections.create_connection(hosts=['https://localhost:9200'], request_timeout=20)
  8. Connect to multiple nodes

    main

    To distribute work across the cluster and avoid overloading a single node, you can pass a list of node URLs to the client. The client will use these URLs as separate nodes in the connection pool. By default, nodes are selected using a round-robin strategy.

    Note: If your cluster is behind a load balancer (like Elastic Cloud), you should use the load balancer's host and port instead of a list of individual nodes.

    import os
    from elasticsearch import Elasticsearch
    
    NODES = [
        "https://localhost:9200",
        "https://localhost:9201",
        "https://localhost:9202",
    ]
    
    ELASTIC_PASSWORD = os.environ['ELASTIC_PASSWORD']
    
    client = Elasticsearch(
        NODES,
        ca_certs="/path/to/http_ca.crt",
        basic_auth=("elastic", ELASTIC_PASSWORD)
    )
  9. Use ES|QL functions with Python wrappers

    main

    All ES|QL functions have Python wrappers available in the elasticsearch.esql.functions module. When using these wrappers in Python-based expressions, wrap field names or other expressions in the E() helper function.

    Example using functions.length():

    from elasticsearch.esql import ESQL, functions, E
    
    query = (
        ESQL.from_("employees")
        .keep("first_name", "last_name", "height")
        .where(functions.length(E("first_name")) < 4)
    )
  10. Explore complex Python DSL examples

    main

    For complex usage patterns involving the Elasticsearch Domain Specific Language (DSL) module, refer to the official examples directory in the repository. These examples demonstrate how to construct sophisticated queries and aggregations using the Python DSL module.

    https://github.com/elastic/elasticsearch-py/tree/master/examples/dsl