: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): read hogql metrics tables from metrics4 (#106767)
Frank Hamand86d018d41996
diff --git a/posthog/hogql/database/schema/metrics.py b/posthog/hogql/database/schema/metrics.pyindex 0d776065acd5..89a2fd3dd1fd 100644--- a/posthog/hogql/database/schema/metrics.py+++ b/posthog/hogql/database/schema/metrics.py@@ -100,7 +100,7 @@ class MetricsTable(Table):}def to_printed_clickhouse(self, context):- return "metrics_distributed"+ return "metrics4_view"def to_printed_hogql(self):return "metrics"@@ -142,7 +142,7 @@ class MetricSeriesTable(Table):),"attributes": MapStringDatabaseField(name="attributes", nullable=False),"last_seen": DateTimeDatabaseField(- name="last_seen", nullable=False, description="Most recent sample timestamp seen for this series."+ name="timestamp", nullable=False, description="Most recent sample timestamp seen for this series."),"original_expiry_timestamp": DateTimeDatabaseField(name="original_expiry_timestamp", nullable=False, description="When the series leaves retention."@@ -150,7 +150,7 @@ class MetricSeriesTable(Table):}def to_printed_clickhouse(self, context):- return "metric_series_distributed"+ return "metrics4_series"def to_printed_hogql(self):return "metric_series"@@ -167,6 +167,7 @@ class MetricAttributesTable(Table):nullable=False,description="Coarse time bucket the attribute counts are aggregated over.",),+ "metric_name": StringDatabaseField(name="metric_name", nullable=False),"attribute_key": StringDatabaseField(name="attribute_key", nullable=False, description="Metric attribute name."),@@ -192,7 +193,7 @@ class MetricAttributesTable(Table):}def to_printed_clickhouse(self, context):- return "metric_attributes_distributed"+ return "metrics4_attributes"def to_printed_hogql(self):return "metric_attributes"diff --git a/posthog/hogql/printer/utils.py b/posthog/hogql/printer/utils.pyindex 90f4b4210cb1..be320ebd2788 100644--- a/posthog/hogql/printer/utils.py+++ b/posthog/hogql/printer/utils.py@@ -38,6 +38,7 @@ from posthog.hogql.transforms.json_property_pushdown import ()from posthog.hogql.transforms.lazy_tables import resolve_lazy_tablesfrom posthog.hogql.transforms.logical_property_lowering import lower_property_access+from posthog.hogql.transforms.metrics_time_bucket_bounds import add_metrics_time_bucket_boundsfrom posthog.hogql.transforms.projection_pushdown import pushdown_projectionsfrom posthog.hogql.transforms.property_types import PropertySwapper, build_property_swapperfrom posthog.hogql.transforms.type_aware_simplification import (@@ -419,6 +420,10 @@ def prepare_ast_for_printing(with context.timings.measure("events_read_in_order"):node = order_events_reads_by_sort_key(node)+ # After property resolution, so the timestamp column is already wrapped and every table type is final.+ with context.timings.measure("metrics_time_bucket_bounds"):+ node = add_metrics_time_bucket_bounds(node)+# We support global query settings, and local subquery settings.# If the global query is a select query with settings, merge the two.if isinstance(node, ast.SelectQuery) and node.settings is not None and settings is not None:diff --git a/posthog/hogql/transforms/metrics_time_bucket_bounds.py b/posthog/hogql/transforms/metrics_time_bucket_bounds.pynew file mode 100644index 000000000000..84db6d293c6a--- /dev/null+++ b/posthog/hogql/transforms/metrics_time_bucket_bounds.py@@ -0,0 +1,137 @@+"""Add ``time_bucket`` bounds that match each ``timestamp`` bound on the ``metrics`` table.++``metrics`` reads ``metrics4_view``. Its ``metrics4_samples`` part stores the points of one series-hour in arrays,+and ``timestamp`` exists only after the ``ARRAY JOIN``. ClickHouse cannot use a ``timestamp`` filter to skip parts,+so a two-hour query reads all rows of the team. The sort key contains ``time_bucket``, the start of the UTC hour of+each point, so a ``time_bucket`` bound skips parts.++For a top-level ``AND`` term that compares ``metrics.timestamp`` with an expression without columns, the transform+adds a ``time_bucket`` term with the hour of the bound:++ timestamp >= x or timestamp > x -> time_bucket >= toStartOfHour(toTimeZone(x, 'UTC'))+ timestamp <= x or timestamp < x -> time_bucket <= toStartOfHour(toTimeZone(x, 'UTC'))++Each new term is true for every row that the ``timestamp`` term keeps, so no result changes. ``toTimeZone`` makes+sure that time zones with a half-hour offset round to the UTC hour.+"""++from posthog.hogql import ast+from posthog.hogql.base import _T_AST+from posthog.hogql.database.schema.metrics import MetricsTable+from posthog.hogql.visitor import TraversingVisitor, clone_expr++_LOWER_BOUND_OPS = (ast.CompareOperationOp.Gt, ast.CompareOperationOp.GtEq)+_UPPER_BOUND_OPS = (ast.CompareOperationOp.Lt, ast.CompareOperationOp.LtEq)+_FLIPPED_OPS = {+ ast.CompareOperationOp.Gt: ast.CompareOperationOp.Lt,+ ast.CompareOperationOp.GtEq: ast.CompareOperationOp.LtEq,+ ast.CompareOperationOp.Lt: ast.CompareOperationOp.Gt,+ ast.CompareOperationOp.LtEq: ast.CompareOperationOp.GtEq,+}+++def add_metrics_time_bucket_bounds(node: _T_AST) -> _T_AST:+ """Add the bounds to every select in the tree. Mutates in place and returns the node."""+ _MetricsTimeBucketBoundsTransform().visit(node)+ return node+++class _MetricsTimeBucketBoundsTransform(TraversingVisitor):+ def visit_select_query(self, node: ast.SelectQuery) -> None:+ super().visit_select_query(node)+ node.where = _with_bounds(node.where)+ node.prewhere = _with_bounds(node.prewhere)+++def _with_bounds(where: ast.Expr | None) -> ast.Expr | None:+ if where is None:+ return None+ terms = _and_terms(where)+ bounds = [bound for term in terms if (bound := _time_bucket_bound(term)) is not None]+ bounds = [bound for bound in bounds if not any(_same_bound(bound, term) for term in terms)]+ if not bounds:+ return where+ return ast.And(exprs=[*terms, *bounds])+++def _and_terms(expr: ast.Expr) -> list[ast.Expr]:+ if isinstance(expr, ast.And):+ return [term for sub in expr.exprs for term in _and_terms(sub)]+ return [expr]+++def _time_bucket_bound(term: ast.Expr) -> ast.CompareOperation | None:+ if not isinstance(term, ast.CompareOperation) or term.op not in _FLIPPED_OPS:+ return None+ field, bound, op = _metrics_timestamp_field(term.left), term.right, term.op+ if field is None:+ field, bound, op = _metrics_timestamp_field(term.right), term.left, _FLIPPED_OPS[term.op]+ if field is None or _has_field(bound):+ return None++ assert isinstance(field.type, ast.FieldType)+ time_bucket = ast.Field(+ chain=[*field.chain[:-1], "time_bucket"],+ type=ast.FieldType(name="time_bucket", table_type=field.type.table_type),+ )+ hour = ast.Call(+ name="toStartOfHour",+ args=[ast.Call(name="toTimeZone", args=[clone_expr(bound, clear_types=False), ast.Constant(value="UTC")])],+ )+ new_op = ast.CompareOperationOp.GtEq if op in _LOWER_BOUND_OPS else ast.CompareOperationOp.LtEq+ return ast.CompareOperation(left=time_bucket, op=new_op, right=hour)+++def _metrics_timestamp_field(expr: ast.Expr) -> ast.Field | None:+ # The property-type pass has already wrapped the column in toTimeZone.+ while isinstance(expr, ast.Alias):+ expr = expr.expr+ if isinstance(expr, ast.Call) and expr.name == "toTimeZone" and expr.args:+ expr = expr.args[0]+ while isinstance(expr, ast.Alias):+ expr = expr.expr+ if not isinstance(expr, ast.Field) or not _is_metrics_field(expr.type, "timestamp"):+ return None+ return expr+++def _is_metrics_field(type_: ast.Type | None, name: str) -> bool:+ # A computed select alias named `timestamp` resolves to its expression's type, not to the metrics FieldType.+ while isinstance(type_, ast.FieldAliasType):+ type_ = type_.type+ if not isinstance(type_, ast.FieldType) or type_.name != name:+ return False+ table_type = type_.table_type+ while isinstance(table_type, ast.TableAliasType):+ table_type = table_type.table_type+ return isinstance(table_type, ast.TableType) and isinstance(table_type.table, MetricsTable)+++def _same_bound(bound: ast.CompareOperation, term: ast.Expr) -> bool:+ # Running the transform twice adds nothing: the second pass finds the terms of the first.+ return (+ isinstance(term, ast.CompareOperation)+ and term.op == bound.op+ and isinstance(term.left, ast.Field)+ and _is_metrics_field(term.left.type, "time_bucket")+ and clone_expr(term.right, clear_types=True, clear_locations=True)+ == clone_expr(bound.right, clear_types=True, clear_locations=True)+ )+++class _FieldFinder(TraversingVisitor):+ def __init__(self) -> None:+ super().__init__()+ self.found = False++ def visit_field(self, node: ast.Field) -> None:+ self.found = True++ def visit_select_query(self, node: ast.SelectQuery) -> None:+ self.found = True+++def _has_field(expr: ast.Expr) -> bool:+ finder = _FieldFinder()+ finder.visit(expr)+ return finder.founddiff --git a/posthog/hogql/transforms/test/test_metrics_time_bucket_bounds.py b/posthog/hogql/transforms/test/test_metrics_time_bucket_bounds.pynew file mode 100644index 000000000000..7094736911d6--- /dev/null+++ b/posthog/hogql/transforms/test/test_metrics_time_bucket_bounds.py@@ -0,0 +1,46 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.hogql.context import HogQLContext+from posthog.hogql.parser import parse_select+from posthog.hogql.printer import prepare_and_print_ast+++class TestMetricsTimeBucketBounds(BaseTest):+ def _print(self, query: str) -> str:+ context = HogQLContext(team_id=self.team.pk, team=self.team, enable_select_queries=True)+ return prepare_and_print_ast(parse_select(query), context, "clickhouse")[0]++ @parameterized.expand(+ [+ ("gte", "timestamp >= now() - INTERVAL 2 HOUR", "greaterOrEquals(metrics4_view.time_bucket"),+ ("gt", "timestamp > now() - INTERVAL 2 HOUR", "greaterOrEquals(metrics4_view.time_bucket"),+ ("lt", "timestamp < now()", "lessOrEquals(metrics4_view.time_bucket"),+ ("lte", "timestamp <= now()", "lessOrEquals(metrics4_view.time_bucket"),+ ("flipped", "now() - INTERVAL 2 HOUR <= timestamp", "greaterOrEquals(metrics4_view.time_bucket"),+ ("literal", "timestamp >= toDateTime('2026-09-25 10:17:00')", "greaterOrEquals(metrics4_view.time_bucket"),+ ]+ )+ def test_adds_hour_bound(self, _name: str, where: str, expected: str):+ sql = self._print(f"SELECT count() FROM posthog.metrics WHERE team_id = 1 AND {where}")+ assert expected in sql+ assert "toStartOfHour(toTimeZone(" in sql++ def test_adds_both_bounds_with_table_alias(self):+ sql = self._print(+ "SELECT count() FROM posthog.metrics AS m WHERE m.timestamp >= now() - INTERVAL 1 HOUR AND m.timestamp < now()"+ )+ assert "greaterOrEquals(m.time_bucket" in sql+ assert "lessOrEquals(m.time_bucket" in sql++ @parameterized.expand(+ [+ ("column_bound", "SELECT count() FROM posthog.metrics WHERE timestamp >= observed_timestamp"),+ ("inside_or", "SELECT count() FROM posthog.metrics WHERE timestamp >= now() OR value > 1"),+ ("equality", "SELECT count() FROM posthog.metrics WHERE timestamp = now()"),+ ("other_table", "SELECT count() FROM events WHERE timestamp >= now()"),+ ]+ )+ def test_leaves_other_filters_alone(self, _name: str, query: str):+ assert "time_bucket" not in self._print(query)diff --git a/posthog/tasks/alerts/test/test_metrics_alerts.py b/posthog/tasks/alerts/test/test_metrics_alerts.pyindex 62fcf7601b8a..8993909f7e15 100644--- a/posthog/tasks/alerts/test/test_metrics_alerts.py+++ b/posthog/tasks/alerts/test/test_metrics_alerts.py@@ -28,7 +28,7 @@ from products.metrics.backend.facade.contracts import (from products.metrics.backend.facade.testing import seed_metric# 08:55 — the 08:00 hourly bucket is still accumulating; 07:00 is the last complete one.-FROZEN_TIME = dateutil.parser.parse("2026-07-01T08:55:00.000Z")+FROZEN_TIME = dateutil.parser.parse("2026-09-19T08:55:00.000Z")def _metrics_flag_only(flag: str, *args: Any, **kwargs: Any) -> bool:@@ -40,10 +40,10 @@ def _stub_investigation_result(metric_name: str, mover_label: str = "pod-1") ->metric_name=metric_name,aggregation="avg",interval="1 minute",- baseline_from="2026-07-01T05:00:00+00:00",- baseline_to="2026-07-01T06:00:00+00:00",- anomaly_from="2026-07-01T06:00:00+00:00",- anomaly_to="2026-07-01T07:00:00+00:00",+ baseline_from="2026-09-19T05:00:00+00:00",+ baseline_to="2026-09-19T06:00:00+00:00",+ anomaly_from="2026-09-19T06:00:00+00:00",+ anomaly_to="2026-09-19T07:00:00+00:00",baseline_mean=5.0,baseline_stddev=0.5,anomaly_mean=50.0,@@ -131,7 +131,7 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):metric_name=self.metric_name,metric_type="gauge",points=[- (dt.datetime(2026, 7, 1, hour, 30, tzinfo=dt.UTC), value) for hour, value in values_by_hour.items()+ (dt.datetime(2026, 9, 19, hour, 30, tzinfo=dt.UTC), value) for hour, value in values_by_hour.items()],labels=labels or {},)@@ -220,7 +220,7 @@ class TestMetricsAlerts(APIBaseTest, ClickhouseTestMixin):team_id=self.team.pk,metric_name=divisor_metric,metric_type="gauge",- points=[(dt.datetime(2026, 7, 1, hour, 30, tzinfo=dt.UTC), 10.0) for hour in (6, 7)],+ points=[(dt.datetime(2026, 9, 19, hour, 30, tzinfo=dt.UTC), 10.0) for hour in (6, 7)],labels={},)insight = self.create_metrics_insight(diff --git a/products/metrics/backend/tests/_seeder.py b/products/metrics/backend/tests/_seeder.pyindex 4e5c76a0948e..bed3cd4c4cfa 100644--- a/products/metrics/backend/tests/_seeder.py+++ b/products/metrics/backend/tests/_seeder.py@@ -1,11 +1,12 @@-"""Test-only metric row seeder for the metrics2 chain.+"""Test-only metric row seeder for the metrics2 and metrics4 chains.-Inserts rows into `metrics2_input` via `sync_execute` rather than driving the+Inserts rows into `metrics2_input` and `metrics4_input` via `sync_execute` rather than driving theOTLP pipe, so tests don't depend on capture-logs + metrics-ingestion-consumerrunning. `metrics2_input` is the Null-engine table the Kafka MV writes to, so oneinsert fans out through the same MVs production uses: `metrics2` (data points),`metric_series2` (labels, one row per series) and `metric_attributes2` (the-attribute rollups).+attribute rollups). The `metrics4_input` insert fills the metrics4 tables that+HogQL reads.The shape mirrors what `rust/capture-logs/src/metric_record.rs` emits — everyquery-runner test (filters, group-by, rate, histogram_quantile) leans on this@@ -59,7 +60,15 @@ def _series_fingerprint(def truncate_metrics_tables() -> None:"""Clear every table the seeder's inserts fan out into, so leftovers can'tleak between tests."""- for table in ("metrics2", "metric_series2", "metric_attributes2"):+ for table in (+ "metrics2",+ "metric_series2",+ "metric_attributes2",+ "metrics4_samples",+ "metrics4_series",+ "metrics4_names",+ "metrics4_attributes",+ ):sync_execute(f"TRUNCATE TABLE IF EXISTS {table}")@@ -142,7 +151,9 @@ def seed_metric()payload = "\n".join(json.dumps(row) for row in rows)- sync_execute(f"INSERT INTO metrics2_input FORMAT JSONEachRow {payload}")+ # HogQL reads the metrics4 tables. The metrics2 chain stays seeded for the readers that still use it.+ for input_table in ("metrics2_input", "metrics4_input"):+ sync_execute(f"INSERT INTO {input_table} FORMAT JSONEachRow {payload}")def seed_metric_event(diff --git a/products/metrics/backend/tests/test_diagnostics.py b/products/metrics/backend/tests/test_diagnostics.pyindex ef917d928465..191b16bf2466 100644--- a/products/metrics/backend/tests/test_diagnostics.py+++ b/products/metrics/backend/tests/test_diagnostics.py@@ -9,7 +9,7 @@ from products.metrics.backend.diagnostics import decompose_bucketfrom products.metrics.backend.fundamentals import SpatialReducer, TemporalReducerfrom products.metrics.backend.tests._seeder import seed_metric, truncate_metrics_tables-BUCKET = dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=dt.UTC)+BUCKET = dt.datetime(2026, 9, 15, 0, 0, 0, tzinfo=dt.UTC)class TestBucketDecomposition(ClickhouseTestMixin, APIBaseTest):diff --git a/products/metrics/backend/tests/test_has_metrics_query_runner.py b/products/metrics/backend/tests/test_has_metrics_query_runner.pyindex c9010a21d140..9d44836ace29 100644--- a/products/metrics/backend/tests/test_has_metrics_query_runner.py+++ b/products/metrics/backend/tests/test_has_metrics_query_runner.py@@ -15,7 +15,7 @@ def _insert_metric_row(*, team_id: int) -> None:seed_metric(team_id=team_id,metric_name="test.metric",- points=[(dt.datetime(2026, 5, 27, tzinfo=dt.UTC), 1.0)],+ points=[(dt.datetime(2026, 9, 18, tzinfo=dt.UTC), 1.0)],)diff --git a/products/metrics/backend/tests/test_metric_event_samples_query_runner.py b/products/metrics/backend/tests/test_metric_event_samples_query_runner.pyindex 4016d41c7043..a5603a5b83b0 100644--- a/products/metrics/backend/tests/test_metric_event_samples_query_runner.py+++ b/products/metrics/backend/tests/test_metric_event_samples_query_runner.py@@ -29,10 +29,14 @@ SPAN_A_B64 = base64.b64encode(bytes.fromhex(SPAN_A_HEX)).decode()def _insert_orphan_sample(*, team_id: int, metric_name: str, timestamp: dt.datetime, value: float) -> None:- # Straight into `metrics2`, bypassing the ingest MVs, so no series row exists.+ # Straight into `metrics4_samples`, bypassing the ingest MVs, so no series row exists.+ # ARRAY JOIN needs every point array to have the same length.sync_execute(- "INSERT INTO metrics2 (team_id, metric_name, series_fingerprint, timestamp, original_expiry_timestamp, value) "- "VALUES (%(team_id)s, %(metric_name)s, 42, %(ts)s, '2200-01-01 00:00:00', %(value)s)",+ "INSERT INTO metrics4_samples (team_id, metric_name, time_bucket, series_fingerprint, original_expiry_date, "+ "timestamp_arr, observed_timestamp_arr, value_arr, count_arr, histogram_counts_arr, trace_id_arr, span_id_arr, "+ "trace_flags_arr) "+ "VALUES (%(team_id)s, %(metric_name)s, toStartOfHour(toDateTime64(%(ts)s, 6)), 42, '2200-01-01', "+ "[toDateTime64(%(ts)s, 6)], [toDateTime64(%(ts)s, 6)], [%(value)s], [1], [[]], [''], [''], [0])",{"team_id": team_id,"metric_name": metric_name,diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.pyindex d59db705c736..c9bd4dbc3c06 100644--- a/products/metrics/backend/tests/test_metric_query_runner.py+++ b/products/metrics/backend/tests/test_metric_query_runner.py@@ -46,13 +46,13 @@ class TestPickInterval:])def test_pick_interval(self, _name: str, delta: dt.timedelta, expected: str) -> None:- start = dt.datetime(2026, 1, 1, 0, 0, 0, tzinfo=dt.UTC)+ start = dt.datetime(2026, 9, 15, 0, 0, 0, tzinfo=dt.UTC)assert _pick_interval(start, start + delta) == expectedclass TestActiveSinceExpr:def test_keeps_series_within_the_last_seen_buffer(self) -> None:- date_from = dt.datetime(2026, 1, 1, 12, tzinfo=dt.UTC)+ date_from = dt.datetime(2026, 9, 15, 12, tzinfo=dt.UTC)expr = _active_since_expr(date_from)@@ -287,7 +287,7 @@ class TestMetricQueryRunner(ClickhouseTestMixin, APIBaseTest):# In a half-hour time zone, a UTC floor can drop the first bucket.self.team.timezone = "Asia/Kolkata"self.team.save()- bucket_start = dt.datetime(2026, 3, 17, 7, 30, tzinfo=dt.UTC)+ bucket_start = dt.datetime(2026, 9, 17, 7, 30, tzinfo=dt.UTC)seed_metric(team_id=self.team.id,metric_name="m1",diff --git a/products/metrics/backend/tests/test_metrics_query_runner.py b/products/metrics/backend/tests/test_metrics_query_runner.pyindex db7a71372fe0..835759fbd724 100644--- a/products/metrics/backend/tests/test_metrics_query_runner.py+++ b/products/metrics/backend/tests/test_metrics_query_runner.py@@ -51,7 +51,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):groupBy=[MetricsQueryGroupBy(key="namespace")],)],- dateRange=DateRange(date_from="2026-07-01T00:00:00Z", date_to="2026-07-01T01:00:00Z"),+ dateRange=DateRange(date_from="2026-09-19T00:00:00Z", date_to="2026-09-19T01:00:00Z"),interval="minute",formula=None,)@@ -69,7 +69,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert request.interval == "minute"assert (request.date_to - request.date_from) == dt.timedelta(hours=1)- @time_machine.travel("2026-07-01T12:00:00Z", tick=False)+ @time_machine.travel("2026-09-19T12:00:00Z", tick=False)def test_default_date_range_is_last_24_hours(self) -> None:query = MetricsQuery(clauses=[MetricsQueryClause(name="a", metricName="http_requests_total", aggregation="sum")]@@ -79,9 +79,9 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert (request.date_to - request.date_from) == dt.timedelta(hours=24)- @time_machine.travel("2026-07-01T12:00:00Z", tick=False)+ @time_machine.travel("2026-09-19T12:00:00Z", tick=False)def test_calculate_returns_one_series_per_group(self) -> None:- base = dt.datetime(2026, 7, 1, 11, 30, tzinfo=dt.UTC)+ base = dt.datetime(2026, 9, 19, 11, 30, tzinfo=dt.UTC)for container, value in (("capture", 5.0), ("ingestion", 7.0)):seed_metric(team_id=self.team.pk,@@ -100,7 +100,7 @@ class TestMetricsQueryRunner(ClickhouseTestMixin, APIBaseTest):groupBy=[MetricsQueryGroupBy(key="container")],)],- dateRange=DateRange(date_from="2026-07-01T11:00:00Z", date_to="2026-07-01T12:00:00Z"),+ dateRange=DateRange(date_from="2026-09-19T11:00:00Z", date_to="2026-09-19T12:00:00Z"),)response = self._runner(query).calculate()