Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add 1 missing tables to the Elasticsearch source (#118024)

Tom Owers36bba4993adf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index baa88adf6750..0c4d6959de11 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4178,7 +4178,7 @@ Today (1): `<non-system index>`
Diffed against: <https://raw.githubusercontent.com/elastic/elasticsearch-specification/main/output/openapi/elasticsearch-openapi.json>
-- [ ] `Data stream documents (GET /{index}/_search, discovered via GET /_data_stream)` — import logs, events, and metrics stored in data streams whose hidden backing indices do not appear as source tables (high)
+- [x] `Data stream documents (GET /{index}/_search, discovered via GET /_data_stream)` — import logs, events, and metrics stored in data streams whose hidden backing indices do not appear as source tables (high)
Note: The official OpenAPI spec lists index discovery, data stream discovery, and document search operations. Each discovered non-system index becomes a table; the placeholder represents dynamic names. Official data stream documentation confirms hidden backing indices, which current discovery excludes. Stream documents need separate discovery and logical stream tables; cluster administration and operational health endpoints are excluded.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
index 19fdc2dfe7cc..26d027bd5e6a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
@@ -141,6 +141,43 @@ def list_indices(host: str, auth: ElasticsearchAuth) -> list[str]:
return sorted(index for index in indices if index and not index.startswith("."))
+def list_data_streams(host: str, auth: ElasticsearchAuth) -> list[str]:
+ """List non-hidden, non-system data streams.
+
+ Their backing indices are hidden and dot-prefixed, so `list_indices` never returns them.
+ Best-effort: clusters before 7.9 have no data stream API, and credentials without
+ `view_index_metadata` can't list streams, so both yield no streams instead of failing discovery.
+ """
+ response = _get_session(auth).get(f"{normalize_host(host)}/_data_stream", timeout=REQUEST_TIMEOUT_SECONDS)
+ if not response.ok:
+ return []
+ try:
+ body = response.json()
+ except requests.exceptions.JSONDecodeError:
+ return []
+
+ streams = body.get("data_streams") if isinstance(body, dict) else None
+ names = [
+ stream.get("name") or ""
+ for stream in streams or []
+ if isinstance(stream, dict) and not stream.get("hidden") and not stream.get("system")
+ ]
+ return sorted(name for name in names if name and not name.startswith("."))
+
+
+def is_data_stream(session: requests.Session, base_url: str, name: str) -> bool:
+ # A plain index answers 404 here, and a cluster without the data stream API answers 400 or 404.
+ response = session.get(f"{base_url}/_data_stream/{quote(name)}", timeout=REQUEST_TIMEOUT_SECONDS)
+ if not response.ok:
+ return False
+ try:
+ body = response.json()
+ except requests.exceptions.JSONDecodeError:
+ return False
+ streams = body.get("data_streams") if isinstance(body, dict) else None
+ return any(isinstance(stream, dict) and stream.get("name") == name for stream in streams or [])
+
+
def _collect_float_paths(properties: dict[str, Any], prefix: str, paths: set[str]) -> None:
"""Walk an Elasticsearch mapping's `properties` tree, recording dotted paths of float-typed fields."""
for name, spec in properties.items():
@@ -235,10 +272,15 @@ def _build_post_fn(
return post
-def _page_items(data: dict[str, Any], float_paths: set[str]) -> tuple[list, list[dict[str, Any]]]:
+def _page_items(
+ data: dict[str, Any], float_paths: set[str], include_index: bool = False
+) -> tuple[list, list[dict[str, Any]]]:
"""Split a scroll response into its raw hits and the coerced `_source` rows."""
hits = ((data.get("hits") or {}).get("hits")) or []
items = [{**(hit.get("_source") or {}), "_id": hit["_id"]} for hit in hits]
+ if include_index:
+ for item, hit in zip(items, hits):
+ item["_index"] = hit.get("_index")
if float_paths:
for item in items:
coerce_float_fields(item, float_paths)
@@ -258,6 +300,7 @@ def get_rows(
auth: ElasticsearchAuth,
index: str,
logger: FilteringBoundLogger,
+ include_index: bool = False,
) -> Iterator[list[dict[str, Any]]]:
session = _get_session(auth)
base_url = normalize_host(host)
@@ -275,7 +318,7 @@ def get_rows(
try:
while True:
- hits, items = _page_items(data, float_paths)
+ hits, items = _page_items(data, float_paths, include_index)
if items:
yield items
@@ -296,6 +339,9 @@ def elasticsearch_source(
index: str,
logger: FilteringBoundLogger,
) -> SourceResponse:
+ # A data stream only keeps `_id` unique within one backing index, so its rows carry the
+ # backing index and key on both.
+ data_stream = is_data_stream(_get_session(auth), normalize_host(host), index)
return SourceResponse(
name=index,
items=lambda: get_rows(
@@ -303,8 +349,9 @@ def elasticsearch_source(
auth=auth,
index=index,
logger=logger,
+ include_index=data_stream,
),
- primary_keys=["_id"],
+ primary_keys=["_index", "_id"] if data_stream else ["_id"],
partition_count=1,
partition_size=1,
sort_mode="asc",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py
index 71d9fdf6ecbd..71eb01d7f5d8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/source.py
@@ -20,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.elasticsea
ElasticsearchAuth,
elasticsearch_source,
hostname_of,
+ list_data_streams,
list_indices,
validate_credentials as validate_elasticsearch_credentials,
)
@@ -93,7 +94,7 @@ class ElasticsearchSource(SimpleSource[ElasticsearchSourceConfig], ValidateDatab
label="Elasticsearch",
caption="""Connect your Elasticsearch cluster to pull index documents into the PostHog Data warehouse.
-Enter the full cluster URL (e.g. `https://my-deployment.es.us-east-1.aws.found.io:9243`) and credentials with read access to the indices you want to sync. Each non-system index appears as a separate table.""",
+Enter the full cluster URL (e.g. `https://my-deployment.es.us-east-1.aws.found.io:9243`) and credentials with read access to the indices you want to sync. Each non-system index and data stream appears as a separate table.""",
iconPath="/static/services/elasticsearch.png",
docsUrl="https://posthog.com/docs/cdp/sources/elasticsearch",
releaseStatus=ReleaseStatus.ALPHA,
@@ -171,9 +172,11 @@ Enter the full cluster URL (e.g. `https://my-deployment.es.us-east-1.aws.found.i
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Every non-system index is a schema. Generic Elasticsearch has no
- # knowable timestamp field per index, so syncs are full refresh.
- indices = list_indices(config.host, _auth_from_config(config))
+ # Every non-system index and data stream is a schema. Generic Elasticsearch has no
+ # knowable timestamp field per index, and a data stream's `@timestamp` keeps whatever
+ # format each client sent in `_source`, so syncs are full refresh.
+ auth = _auth_from_config(config)
+ indices = sorted({*list_indices(config.host, auth), *list_data_streams(config.host, auth)})
if names is not None:
names_set = set(names)
indices = [index for index in indices if index in names_set]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
index 97e6984e6784..9d3d84e8eef2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
@@ -23,6 +23,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.elasticsea
coerce_float_fields,
elasticsearch_source,
get_float_field_paths,
+ list_data_streams,
list_indices,
normalize_host,
validate_credentials,
@@ -46,6 +47,13 @@ def _driver() -> SourceDriver:
)
+_NOT_A_DATA_STREAM = ScriptedResponse(status=404, json={"error": {"type": "index_not_found_exception"}, "status": 404})
+
+
+def _data_stream_body(*names: str, **flags: bool) -> dict[str, Any]:
+ return {"data_streams": [{"name": name, "hidden": False, "system": False, **flags} for name in names]}
+
+
def _scroll_page(hits: list[dict[str, Any]], scroll_id: str | None = "scroll-1") -> dict[str, Any]:
body: dict[str, Any] = {"hits": {"hits": hits}}
if scroll_id:
@@ -143,12 +151,51 @@ class TestListIndices:
list_indices("https://es.example.com", ElasticsearchAuth(api_key="k"))
+class TestListDataStreams:
+ def test_filters_hidden_system_and_dot_prefixed_streams_and_sorts(self):
+ body = {
+ "data_streams": [
+ {"name": "metrics-app", "hidden": False, "system": False},
+ {"name": "logs-web", "hidden": False, "system": False},
+ {"name": "ilm-history-7", "hidden": True, "system": False},
+ {"name": "fleet-actions", "hidden": False, "system": True},
+ {"name": ".internal-stream", "hidden": False, "system": False},
+ {"name": "", "hidden": False},
+ {"hidden": False},
+ "not-a-dict",
+ ]
+ }
+ with scripted_network([ScriptedResponse(json=body)]) as network:
+ streams = list_data_streams("https://es.example.com", ElasticsearchAuth(api_key="k"))
+
+ assert streams == ["logs-web", "metrics-app"]
+ assert network.requests_log[0].path == "/_data_stream"
+
+ @pytest.mark.parametrize(
+ "response",
+ [
+ # Clusters before 7.9 have no data stream API.
+ ScriptedResponse(status=400, json={"error": {"type": "illegal_argument_exception"}}),
+ ScriptedResponse(status=404, json={}),
+ # Credentials without view_index_metadata can't list streams.
+ ScriptedResponse(status=403, json={"error": {"type": "security_exception"}}),
+ ScriptedResponse(body=b"<html>"),
+ ScriptedResponse(json={"unexpected": True}),
+ ScriptedResponse(json=[]),
+ ],
+ )
+ def test_unavailable_api_yields_no_streams(self, response):
+ with scripted_network([response]):
+ assert list_data_streams("https://es.example.com", ElasticsearchAuth(api_key="k")) == []
+
+
class TestGetRows:
def test_scrolls_until_short_page(self):
full_hits = [{"_id": str(i), "_source": {"value": i}} for i in range(PAGE_SIZE)]
result = _driver().run(
"orders",
[
+ _NOT_A_DATA_STREAM,
ScriptedResponse(json={"orders": {"mappings": {"properties": {}}}}),
ScriptedResponse(json=_scroll_page(full_hits)),
ScriptedResponse(json=_scroll_page([{"_id": "last", "_source": {"value": -1}}])),
@@ -159,14 +206,21 @@ class TestGetRows:
assert result.raised is None
assert len(result.items) == 2
assert result.items[1] == [{"value": -1, "_id": "last"}]
- assert result.paths == ["/orders/_mapping", "/orders/_search", "/_search/scroll", "/_search/scroll"]
- assert result.requests[1].param("scroll") == "5m"
- assert result.requests[2].json() == {"scroll": "5m", "scroll_id": "scroll-1"}
+ assert result.paths == [
+ "/_data_stream/orders",
+ "/orders/_mapping",
+ "/orders/_search",
+ "/_search/scroll",
+ "/_search/scroll",
+ ]
+ assert result.requests[2].param("scroll") == "5m"
+ assert result.requests[3].json() == {"scroll": "5m", "scroll_id": "scroll-1"}
def test_scroll_context_is_cleared_after_walk(self):
result = _driver().run(
"orders",
[
+ _NOT_A_DATA_STREAM,
ScriptedResponse(json={}),
ScriptedResponse(json=_scroll_page([{"_id": "1", "_source": {}}])),
ScriptedResponse(json={}),
@@ -174,9 +228,9 @@ class TestGetRows:
)
assert result.raised is None
- assert [request.method for request in result.requests] == ["GET", "POST", "DELETE"]
- assert result.requests[2].path == "/_search/scroll"
- assert result.requests[2].json() == {"scroll_id": ["scroll-1"]}
+ assert [request.method for request in result.requests] == ["GET", "GET", "POST", "DELETE"]
+ assert result.requests[3].path == "/_search/scroll"
+ assert result.requests[3].json() == {"scroll_id": ["scroll-1"]}
def test_float_typed_fields_are_coerced_across_rows(self):
# A float-typed field whose docs mix whole (40) and fractional (40.5) values must all
@@ -184,6 +238,7 @@ class TestGetRows:
result = _driver().run(
"orders",
[
+ _NOT_A_DATA_STREAM,
ScriptedResponse(
json={"orders": {"mappings": {"properties": {"amount": {"type": "float"}, "id": {"type": "long"}}}}}
),
@@ -209,6 +264,57 @@ class TestGetRows:
assert [type(row["amount"]) for row in result.rows] == [float, float]
assert [type(row["id"]) for row in result.rows] == [int, int]
+ def test_data_stream_rows_carry_backing_index(self):
+ backing_mapping = {"properties": {"@timestamp": {"type": "date"}, "latency": {"type": "double"}}}
+ result = _driver().run(
+ "logs-web",
+ [
+ ScriptedResponse(json=_data_stream_body("logs-web")),
+ ScriptedResponse(
+ json={
+ ".ds-logs-web-2099.01.01-000001": {"mappings": backing_mapping},
+ ".ds-logs-web-2099.01.02-000002": {"mappings": backing_mapping},
+ }
+ ),
+ ScriptedResponse(
+ json=_scroll_page(
+ [
+ {
+ "_index": ".ds-logs-web-2099.01.01-000001",
+ "_id": "same-id",
+ "_source": {"@timestamp": "2099-01-01T10:00:00Z", "latency": 3},
+ },
+ {
+ "_index": ".ds-logs-web-2099.01.02-000002",
+ "_id": "same-id",
+ "_source": {"@timestamp": "2099-01-02T10:00:00Z", "latency": 3.5},
+ },
+ ]
+ )
+ ),
+ ScriptedResponse(json={}),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.response is not None
+ assert result.response.primary_keys == ["_index", "_id"]
+ assert result.rows == [
+ {
+ "@timestamp": "2099-01-01T10:00:00Z",
+ "latency": 3.0,
+ "_id": "same-id",
+ "_index": ".ds-logs-web-2099.01.01-000001",
+ },
+ {
+ "@timestamp": "2099-01-02T10:00:00Z",
+ "latency": 3.5,
+ "_id": "same-id",
+ "_index": ".ds-logs-web-2099.01.02-000002",
+ },
+ ]
+ assert result.paths[:3] == ["/_data_stream/logs-web", "/logs-web/_mapping", "/logs-web/_search"]
+
class TestFloatFieldPaths:
@pytest.mark.parametrize(
@@ -296,13 +402,27 @@ class TestCoerceFloatFields:
class TestElasticsearchSourceResponse:
- def test_response_metadata(self):
- response = elasticsearch_source(
- "https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock()
- )
+ @pytest.mark.parametrize(
+ "detect_response, expected_primary_keys",
+ [
+ (_NOT_A_DATA_STREAM, ["_id"]),
+ (ScriptedResponse(json=_data_stream_body("orders")), ["_index", "_id"]),
+ # Only an exact name match counts as a data stream.
+ (ScriptedResponse(json=_data_stream_body("orders-archive")), ["_id"]),
+ # Credentials without view_index_metadata fall back to the plain index key.
+ (ScriptedResponse(status=403, json={"error": {"type": "security_exception"}}), ["_id"]),
+ (ScriptedResponse(body=b"<html>"), ["_id"]),
+ ],
+ )
+ def test_response_metadata(self, detect_response, expected_primary_keys):
+ with scripted_network([detect_response]) as network:
+ response = elasticsearch_source(
+ "https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock()
+ )
+ assert network.requests_log[0].path == "/_data_stream/orders"
assert response.name == "orders"
- assert response.primary_keys == ["_id"]
+ assert response.primary_keys == expected_primary_keys
assert response.sort_mode == "asc"
assert response.partition_mode is None
assert response.partition_keys is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py
index 7eb68eb04ae4..85c7be48a6ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch_source.py
@@ -44,13 +44,31 @@ class TestElasticsearchSource:
self.team_id = 123
self.config = _config()
+ @pytest.mark.parametrize(
+ "indices, data_streams, names, expected",
+ [
+ (
+ ["orders", "accounts"],
+ ["metrics-app", "logs-web"],
+ None,
+ ["accounts", "logs-web", "metrics-app", "orders"],
+ ),
+ (["orders"], [], None, ["orders"]),
+ ([], ["logs-web"], None, ["logs-web"]),
+ (["accounts", "orders"], ["logs-web"], ["orders", "logs-web"], ["logs-web", "orders"]),
+ ],
+ )
+ @mock.patch(f"{_SOURCE_MODULE}.list_data_streams")
@mock.patch(f"{_SOURCE_MODULE}.list_indices")
- def test_get_schemas_filtered_by_names(self, mock_list):
- mock_list.return_value = ["accounts", "orders"]
+ def test_get_schemas_lists_indices_and_data_streams(
+ self, mock_indices, mock_streams, indices, data_streams, names, expected
+ ):
+ mock_indices.return_value = indices
+ mock_streams.return_value = data_streams
- schemas = self.source.get_schemas(self.config, self.team_id, names=["orders"])
+ schemas = self.source.get_schemas(self.config, self.team_id, names=names)
- assert [s.name for s in schemas] == ["orders"]
+ assert [s.name for s in schemas] == expected
@mock.patch(f"{_SOURCE_MODULE}.validate_elasticsearch_credentials")
@mock.patch.object(ElasticsearchSource, "is_database_host_valid")