Skip to main content

PyPi CI Code coverage Python Issues Commit activity Downloads License

☀️ ray-elasticsearch

Ray data source and sink for Elasticsearch.

Use this minimal library if you plan to read or write data from/to Elasticsearch massively parallel for data processing in Ray. Internally, the library uses parallelized sliced point-in-time search for reading and parallelized bulk requests for writing data, the two most efficient ways to read/write data to/from Elasticsearch. Note, that this library does not guarantee any specific ordering of the results, though, the scores are returned.

Installation

Install the package from PyPI, e.g., with uv:

pip install ray-elasticsearch
# Or install with uv:
uv add ray-elasticsearch 

Usage

This library makes use of Ray's Datasource and Datasink APIs. For reading, use ElasticsearchDatasource and, for writing, use ElasticsearchDatasink.

Read documents

You can read results from a specified index by using an ElasticsearchDatasource with Ray's read_datasource(). Considering you have an index named test that stores some numeric value in the value field, you can efficiently compute the sum of all values like so:

from ray import init
from ray.data import read_datasource
from ray_elasticsearch import ElasticsearchDatasource

init()
source = ElasticsearchDatasource(index="test")
res = read_datasource(source)\
    .sum("value")
print(f"Read complete. Sum: {res}")

Use an Elasticsearch query to filter the results:

source = ElasticsearchDatasource(
    index="test",
    query={
        "match": {
            "text": "foo bar",
        },
    },
)

Note that the parallel read does not enforce any ordering of the results even though the results are scored by Elasticsearch. With the default settings, you can still access the retrieved score from the Ray Dataset's _score column.

You do not need to set a fixed maximum concurrency level. But it can often be a good idea to limit concurrency (and hence, simultaneous requests to the Elasticsearch cluster) by setting the override_num_blocks parameter in Ray's read_datasource():

source = ElasticsearchDatasource(index="test")
ds = read_datasource(source, override_num_blocks=100)

The override_num_blocks parameter will determine the number of slices for the sliced point-in-time request. In typical scenarios, this number should not be much larger than 1000. Even with hundreds or thousands of slices, you can still limit how many requests are sent to the Elasticsearch cluster in parallel with Ray's concurrency parameter:

source = ElasticsearchDatasource(index="test")
ds = read_datasource(source, override_num_blocks=1000, concurrency=100)

Normally, it suffices to just set override_num_blocks reasonably small, e.g., to 100 or to the number of Elasticsearch data nodes in the cluster, and to keep the concurrency unchanged.

Write documents

Writing documents works similarly by using the ElasticsearchDatasink with Ray's write_datasink():

from ray import init
from ray.data import range
from ray_elasticsearch import ElasticsearchDatasink

init()
sink = ElasticsearchDatasink(index="test")
range(10_000) \
    .rename_columns({"id": "value"}) \
    .write_datasink(sink)
print("Write complete.")

Write concurrency can be limited by specifying the concurrency parameter in Ray's write_datasink(). It is advisable to keep the concurrency at or below the number of data nodes in the Elasticsearch cluster, e.g., at 100.

Elasticsearch connection and authentication

Per default, the data source and sink access Elasticsearch on localhost:9200, the default of the elasticsearch Python library. However, in most cases, you would instead want to continue to some remote Elasticsearch instance. To do so, specify the client like in the example below, and use the same parameters as in the Elasticsearch() constructor:

source = ElasticsearchDatasource(
    index="test",
    hosts="<HOST>",
    http_auth=("<USERNAME>", "<PASSWORD>"),
    max_retries=10,
)

All client related keyword arguments to the ElasticsearchDatasource or ElasticsearchDatasink are passed on as is to the Elasticsearch() constructor. Refer to the documentation for an overview of the supported connection settings.

Data schema auto-guessing

The ElasticsearchDatasource will internally get the mapping for the given index from Elasticsearch, and guess the PyArrow data schema based on Elasticsearch's mapping field types.

Elasticsearch DSL

This library integrates well with the Elasticsearch DSL library, to simplify building queries, to derive a more accurate data schema from a Document class, or to simplify transforming data from Elasticsearch data sources in Ray.

Query DSL

To simplify query construction, just use any of the query classes from the Elasticsearch DSL library:

from elasticsearch_dsl.query import Exists
from ray_elasticsearch import ElasticsearchDatasource

source = ElasticsearchDatasource(
    index="foo",
    query=Exists(field="doi"),
)

All usual operators to combine queries are supported.

Document mapping and index

This library can also improve the schema auto-guessing capabilities, by using an Elasticsearch DSL Document class:

from elasticsearch_dsl import Document
from ray_elasticsearch import ElasticsearchDatasource

class Foo(Document):
    text = Text(required=True)
    class Index:
        name = "test_foo"

source = ElasticsearchDatasource(index=Foo)

Most importantly, this will make the schema reflect the required and multi properties of the Document's fields to set PyArrow's nullable argument and/or wrap schema field types as lists.

Date fields (date and date_nanos) become a UTC PyArrow timestamp (with microsecond precision). Only the default format or a single ISO 8601 format (e.g., strict_date_optional_time, strict_date_time_no_millis, or strict_date) or epoch_millis is supported. Other formats, including format chains (e.g., strict_date||epoch_millis) and custom patterns (e.g., yyyy/MM/dd), raise an error. When reading, numbers are parsed as epoch milliseconds and strings as ISO 8601 dates, where dates without time zone are interpreted as UTC (like Elasticsearch does).

Note that, the rows returned by an ElasticsearchDatasource, even if using a Document class as index or schema, will still be dictionaries. Due to the way Ray stores the data internally (in PyArrow format), we cannot directly return instances of the given Document class. Use the provided function decorators to still easily transform the data.

Simplified data transformations

Two function decorators are provided that help you with transforming the data from an ElasticsearchDatasource:

@unwrap_document(Foo)
def add_custom_field(row: dict[str, Any], document: Foo) -> dict[str, Any]:
    return {**row, "custom": document.text}

ds = ds.map(add_custom_field)

Or to map batches of data:

@unwrap_documents(Foo)
def add_custom_field_batch(batch: DataFrame, documents: Sequence[Foo]) -> DataFrame:
    batch["custom"] = [document.text for document in documents]
    return batch

ds = ds.map_batches(add_custom_field_batch)

Due to the fixed schema of a Ray Dataset, fields that are missing from a document's _source are read as None. When decoding documents, None values are therefore by default treated as missing fields in the unwrap helpers, so that default values (e.g., of Pydantic fields) apply. To keep None values as explicit nulls instead, use null_as_missing=False.

Elasticsearch Pydantic

Instead of the standard Elasticsearch DSL Document class, you can also use the BaseDocument class from the elasticsearch-pydantic library, to add Pydantic validation and type-checking to your Elasticsearch models. As that library is fully compatible with Elasticsearch DSL, its model classes can be used as a drop-in replacement and still support the more accurate data schema guessing (from a BaseDocument class), or simplified data transformations. These features are included in our test suite to regularly check compatibility of both libraries.

Selecting source and meta fields

In Elasticsearch, any document returned from a search request keeps the actual data nested in the _source field, and has some metadata (e.g., _id and _index) on the top level. However, working with nested columns is tricky with Ray (e.g., nested columns cannot be renamed). The ray-elasticsearch library automatically unwraps the source field. For example, consider the following Elasticsearch record:

{
  "_index": "test",
  "_type": "_doc",
  "_id": "1",
  "_score": null,
  "_source": {
    "value": 1
  }
}

Using the default settings, the corresponding row in the Ray dataset will look like this:

{
    "_index" : "test",
    "_type" : "_doc",
    "_id" : "1",
    "_score" : None,
    "value" : 1
}

You can also select the source and metadata fields explicitly, using the source_fields and meta_fields arguments:

source = ElasticsearchDatasource(
    index="test",
    source_fields=["value"],
    meta_fields=["id"],
)

With the above setting, just the ID and value will be stored in the Ray Dataset's blocks:

{
    "_id" : "1",
    "value" : 1
}

Examples

More examples can be found in the examples directory.

Compatibility

This library works fine with any of the following PyPI packages installed:

The ray-elasticsearch library will automatically detect if the Elasticsearch DSL or Pydantic helpers are installed, and add support for additional features accordingly.

Development

To build this package and contribute to its development you need to install uv.

Development installation

Create and activate a virtual environment, and install the package and test dependencies:

uv venv && source .venv/bin/activate
uv pip install -e .[tests,tests-es7]                # For elasticsearch~=7.0
uv pip install -e .[tests,tests-es7-major]          # For elasticsearch7
uv pip install -e .[tests,tests-es8]                # For elasticsearch~=8.0
uv pip install -e .[tests,tests-es8-major]          # For elasticsearch8
uv pip install -e .[tests,tests-es7-dsl]            # For elasticsearch-dsl~=7.0
uv pip install -e .[tests,tests-es7-dsl-major]      # For elasticsearch7-dsl
uv pip install -e .[tests,tests-es8-dsl]            # For elasticsearch-dsl~=8.0
uv pip install -e .[tests,tests-es8-dsl-major]      # For elasticsearch8-dsl
uv pip install -e .[tests,tests-es7-pydantic]       # For elasticsearch-pydantic and elasticsearch-dsl~=7.0
uv pip install -e .[tests,tests-es7-pydantic-major] # For elasticsearch-pydantic and elasticsearch7-dsl
uv pip install -e .[tests,tests-es8-pydantic]       # For elasticsearch-pydantic and elasticsearch-dsl~=8.0
uv pip install -e .[tests,tests-es8-pydantic-major] # For elasticsearch-pydantic and elasticsearch8-dsl

Testing

Verify your changes against the test suite to verify.

ruff check .  # Code format and LINT
ty check .    # Static typing
pytest .      # Unit tests

Please also add tests for your newly developed code.

Build wheels

Wheels for this package can be built with:

uv build

Support

If you have any problems using this package, please file an issue. We're happy to help!

License

This repository is released under the MIT license.

Metadata

Release files for ray-elasticsearch 1.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ray-elasticsearch 1.3.1
File Size Uploaded Provenance Actions
ray_elasticsearch-1.3.1.tar.gz 31.2 kB With provenance Details for ray_elasticsearch-1.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for ray-elasticsearch 1.3.1
File Interpreter ABI Platform Actions
ray_elasticsearch-1.3.1-py3-none-any.whl Python 3 none any Details for ray_elasticsearch-1.3.1-py3-none-any.whl

Total release size: 57.3 kB

Release files / ray_elasticsearch-1.3.1.tar.gz

Download URL ray_elasticsearch-1.3.1.tar.gz
Size 31.2 kB
Tags Source
SHA-256 checksum
How to use checksums
523416c8f0dd207d53730f7f20d41f3c8e98c81c4934991e38144eea74a8f0d7
BLAKE2b-256 checksum
How to use checksums
8fc7f1d680655233c5632ce7af29b9539fba0620ce6aa4b7d7ca3780ce7703b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Release files / ray_elasticsearch-1.3.1-py3-none-any.whl

Download URL ray_elasticsearch-1.3.1-py3-none-any.whl
Size 26.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5309c61d3c294a98017ddf23142dbaead05c3e8155be120d3ea11e8d3dbe922b
BLAKE2b-256 checksum
How to use checksums
d3e579d876d8f1ce87ce90f8dc1cfa66aa3f064e0480f1d5e520b5cddb708ed9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

Security for ray-elasticsearch 1.3.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for ray_elasticsearch-1.3.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page