Kibana: Querying with KQL, ES|QL & PromQL

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-09 against Kibana 9.5.x. Tested with Elasticsearch 9.5.6 and Kibana 9.5.6 in the hands-on lab (trial licence): the ES|QL queries ran against the lab data, including the lookup join after the lookup index was created; the TS and PROMQL examples need metrics the lab does not hold and were not run.

Kibana speaks three query languages and each has a distinct job. KQL (and Lucene) answers "which documents?": it filters in the query bar of Discover, Lens and dashboards. ES|QL answers "what do the documents add up to?": it filters, aggregates, joins and reshapes in a pipeline, and it is the language of ES|QL visualizations, variable controls and ES|QL rules. PromQL, native in the Elastic Stack since 9.5, lets you query time series metrics with the language Prometheus users already know. This page teaches the monitoring subset of each, shows the same Bookshelf RED questions (rate, errors, duration) in each language, and points out where they differ.

The Elasticsearch-level view of these languages (Query DSL, EQL, SQL, Painless) is on Query Languages & Scripting and is not repeated. The metric and aggregation vocabulary is on Metric Types & Aggregation, the RED method on Monitoring Methods, and the Prometheus side on Prometheus. The Grafana equivalent of this page is Queries, Explore and Drilldown.

Which language for which job

Language Best for Where it runs Limits

KQL

Filtering by field, free text, ranges and nesting in a query bar.

Discover (classic), Lens, dashboard filters, rules that take a KQL filter; also the ES|QL KQL function.

No aggregation, no joins; it only selects documents.

Lucene

Regular expressions, fuzzy matching and other Lucene features.

The same query bars, chosen under Saved query, Language.

Cannot search nested objects or scripted fields.

ES|QL

Aggregations, per-time-bucket metrics, joins, reshaping, thresholds on the result.

Discover, ES|QL visualizations, variable controls, Elasticsearch query rules, Dev Tools, the REST API.

A pipeline language with its own function set; some commands are preview.

PromQL

Existing Prometheus queries and dashboards, rates and histogram quantiles.

The PROMQL source command in ES|QL and a Prometheus-compatible HTTP API.

A documented list of unsupported features (below).

KQL and Lucene for filtering

KQL is a text language for filtering documents, used in the query bar, in the Query DSL kql clause and in the ES|QL KQL function. The rules worth knowing:

  • Free text. A bare value such as Hello searches a default set of fields (those supporting term queries, excluding metadata and nested fields), set by the index.query.default_field index setting.

  • Field and value. http.request.method: GET matches an exact value on keyword, numeric, date and boolean fields; http.request.method: * matches documents where the field has an indexed value.

  • Text fields. Values are analysed: message: null pointer matches the terms in any order, and message: "null pointer" requires the exact phrase.

  • Wildcards. Only * exists, matches zero or more characters and works on string fields; numeric, date, boolean and IP fields reject it with an error. Inside quotation marks the asterisk is literal. Leading wildcards are slow; the query:allowLeadingWildcards setting controls them in Kibana and is unavailable on Serverless.

  • Boolean logic. and, or and not are case-insensitive and parentheses group conditions: http.request.method: (GET or POST).

  • Ranges. http.response.bytes < 10000, and for timestamps @timestamp < now-2w; datetimes containing a colon must be quoted. Each condition on a multi-value field may match a different value.

  • Nested fields. Braces select one nested object: user:{ first: "Alice" and last: "White" }.

  • Escaping. Escape \():<>"*{} with a backslash unless the value is quoted; inside quotes only the quote and the backslash need escaping.

  • Case. Keywords such as and are case-insensitive, but values on keyword fields match exactly, including case, and the Kibana query bar cannot ignore case there.

The one trap is precedence. In the Kibana query bar not binds first, then and, then or. In the Query DSL kql clause and the ES|QL KQL function, and and or have equal precedence and group right to left. A filter pasted from a dashboard into an ES|QL WHERE KQL(...) can change meaning unless it is fully parenthesised. Time zone and default fields differ the same way (the query bar uses the dateFormat:tz setting and index.query.default_field; the other two use options).

service.name : "bookshelf" and severity_text : "ERROR" and not message : "health*"

The example uses the OpenTelemetry field names of the lab logs; check the field list in Discover for the real ones. Lucene is chosen under Saved query, Language, and is the better choice for regular expressions or fuzzy matches, including bracketed ranges such as status:[400 TO 499]; full details are in the Elasticsearch query string syntax.

ES|QL for aggregation

An ES|QL query starts with a source command and continues through processing commands joined by pipes. Source commands are FROM (data streams, indices, aliases, views), TS (time series data streams only) and PROMQL. Keywords are case-insensitive. Kibana supplies the time range: if the data has @timestamp the standard time filter applies automatically, and for another timestamp field use the parameters ?_tstart and ?_tend, which follow the date picker.

STATS and BUCKET

STATS computes aggregations, optionally per group, and each aggregation can carry its own WHERE, which keeps the group and returns a default such as 0 instead of dropping it. BUCKET creates the time buckets for a chart; in an ES|QL visualization give it a target count and the Kibana parameters so the interval adapts to the range:

FROM logs-*.otel-*
| WHERE service.name == "bookshelf"
| STATS errors = COUNT(*) WHERE severity_text == "ERROR",
        total = COUNT(*)
  BY bucket = BUCKET(@timestamp, 50, ?_tstart, ?_tend)
| EVAL error_share = TO_DOUBLE(errors) / total
| SORT bucket

Note the conversion: COUNT returns an integer, so errors / total would be an integer division and give 0 for every bucket. BUCKET picks a size that yields at most the target number of buckets, does not filter rows and does not create empty buckets (the include_empty_buckets option is generally available on Serverless and planned for the Elastic Stack). The count-and-range form is the one to use in Kibana; the fixed-size form takes a duration such as 1 minute.

Source: ES|QL: STATS and BUCKET.

TS for metrics

Metrics need different arithmetic from documents. A counter that resets, or series that report at uneven intervals, give wrong results under FROM | STATS, because raw sums ignore resets and sample density. TS targets only time series data streams and computes an inner function per series first (for example RATE, AVG_OVER_TIME, LAST_OVER_TIME), then aggregates across series. It is generally available since 9.4 (preview in 9.2 and 9.3), and on Serverless. TBUCKET is its bucketing function and TRANGE filters the time window.

TS metrics-*.otel-*
| WHERE TRANGE(1 hour) AND service.name == "bookshelf"
| STATS requests = COUNT(http.server.requests),
        p95 = PERCENTILE(http.server.requests, 95)
  BY TBUCKET(1 minute)

The lab’s Bookshelf stand-in exports traces and logs only, not OTLP metrics, so this query answers Unknown column [http.server.requests] there: it applies to a service that exports OTLP histogram metrics, and the metrics data streams of the lab hold only the APM aggregations that the EDOT Collector derives from the traces.

The shape follows the documented histogram example (COUNT and PERCENTILE over a histogram field by TBUCKET); histogram metrics are generally available since 9.4. The metric name http.server.requests and the dimension service.name are this page’s Bookshelf lab convention, and the exact field names depend on the mapping mode, so confirm them in the Discover metrics grid before pasting. The limits to remember: COUNT(*) after the first STATS counts series rows, not documents; SORT and FORK cannot sit between TS and the first STATS; RATE requires a counter and rejects a gauge; combining metrics whose dimension values do not match can yield nulls; results truncate at 10,000 rows by default; and nested time series functions such as AVG_OVER_TIME(RATE(x)) are an error. WITHOUT(dimension) excludes a dimension from grouping (generally available since 9.4).

Source: ES|QL: TS.

LOOKUP JOIN

LOOKUP JOIN adds columns from a lookup index to each row, matching on one field or a list of fields. The lookup index must use the lookup index mode and be named explicitly (no wildcards). It is generally available since 9.1 (preview in 9.0). A monitoring use is attaching an owning team to a route:

PUT bookshelf-routes
{
  "settings": { "index.mode": "lookup" },
  "mappings": { "properties": { "url.path": { "type": "keyword" }, "owner": { "type": "keyword" } } }
}
FROM traces-*
| WHERE service.name == "bookshelf" AND http.response.status_code >= 500
| LOOKUP JOIN bookshelf-routes ON url.path
| STATS errors = COUNT(*) BY owner

The query was run in the lab after creating the lookup index and adding documents such as { "url.path": "/api/loans", "owner": "loans-team" }; the index name and the owner field are the page’s illustration. If several lookup documents match a row the output has one row per match, so keep the lookup key unique.

Parameters and controls

Variables make a query interactive. Typing ? in the editor offers to create a control: WHERE service.name == ?service selects a value, STATS count = COUNT(*) BY ??field selects a field (the double question mark names a field or function; preview since 9.1), BUCKET(@timestamp, ?interval) selects the interval and STATS metric = ??function selects a function. A control’s values can be static or come from a query, and a query-based control limited with WHERE @timestamp <= ?_tend AND @timestamp > ?_tstart offers only values present in the time range; controls can be chained. Multi-value controls (preview since 9.3) use MV_CONTAINS (all selected values) or MV_INTERSECTS (any). The controls themselves, and how they sit on a dashboard, are on ES|QL Visualizations & Variable Controls and Controls & Drilldowns.

Two cautions: Kibana uses the dateFormat:tz setting for display in Discover, dashboards and Maps, so avoid SET time_zone there because the display and the Elasticsearch calculation can disagree, and ES|QL rules do not read that setting at all and run in UTC unless the rule or cluster sets a time zone, which matters for any query that buckets by day.

Fast mode and approximation

For very large data, ES|QL can compute STATS on a sample and extrapolate. It is a preview on Serverless and in the Elastic Stack since 9.4, and on self-managed and Elastic Cloud Hosted deployments requires an Enterprise subscription. The default sample is about one million rows for STATS ... BY and 100,000 for other STATS; exact results are returned when the data is smaller than the sample or a filter narrows it enough; COUNT_DISTINCT, MIN, MAX and LAST are always exact; results can vary between runs and can drop low-frequency groups. The UI toggle is Fast mode (preview, Stack since 9.5) for a query with exactly one STATS; the query form is the SET directive, and _approximation_confidence_interval(column) returns the 90 percent range.

SET approximation=true;
FROM logs-*.otel-*
| WHERE @timestamp >= NOW() - 30 days
| STATS errors = COUNT(*) WHERE severity_text == "ERROR" BY service.name
| SORT errors DESC

SET approximation=false; forces exact results and SET approximation={"rows":5000000}; raises the sample. Do not approximate the query behind an alert: a threshold decision should rest on exact numbers.

The KQL bar over ES|QL

In Discover’s ES|QL mode the search bar can take KQL: submitting replaces the query with a source command and a WHERE KQL("...") clause and removes other commands, such as KEEP. This is a preview on Serverless and in the Elastic Stack since 9.3; a natural-language mode (preview since 9.5 on the Stack) needs a configured model.

Native PromQL

Since 9.5 the Elastic Stack can run PromQL over time series data streams: generally available on Serverless and on the Stack since 9.5 (preview in 9.4). Elasticsearch parses PromQL into ES|QL plans that run on the same engine as TS, so it is not limited to data from Prometheus: metrics ingested over OTLP or the bulk API work too. Two access methods exist: a Prometheus-compatible HTTP API under /_prometheus/ (which also lets Grafana use Elasticsearch as a Prometheus data source) and the PROMQL source command, which lets you post-process the result with ordinary ES|QL.

PROMQL index=metrics-bookshelf.prometheus-*
  requests=(sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m])))
| SORT step DESC

This query needs a metrics data stream written through the Prometheus remote write endpoint, which the lab’s kibana profile does not create, so it was not run there; on the 9.5.6 lab the same statement without step, buckets or the date picker context answered "unable to create a bucket; provide either step or all of start, end, and buckets", so give a step outside Kibana.

The syntax is PROMQL [option=value ...] [name=](expression). The options are index (default metrics-*), step (derived automatically, exclusive with buckets), buckets (default 100), start and end (default to the Kibana date picker, which you leave out in Kibana), time for an instant query and scrape_interval (default 1m, used for implicit range windows). Naming the expression sets the output column. In Kibana omit start and end so the query follows the date picker, and you may omit the range selector so the window adapts to the step.

The compatibility page lists what does not work, which is where Prometheus users get surprised: subqueries, the @ modifier, selectors without a metric name, and and unless and or with on or ignoring, the functions absent, resets, info, group and count_values, exemplar queries; instant queries use a fixed five-minute lookback, staleness markers are ignored, quantile is approximate (t-digest), and rate and increase are computed over fixed time buckets so results differ slightly from Prometheus. histogram_quantile works on classic _bucket series with an le label and on native histograms (generally available since 9.5), but not over topk, without(...) (planned on the Stack) or with a non-literal first argument: aggregate with by(...) first. Using a time range duration such as [?_tend - ?_tstart] is planned on the Stack. On ingest, metric type is inferred from the name (_total, _sum, _count, _bucket are counters), see Ingesting Monitoring Data.

The Bookshelf RED questions in each language

The three RED questions, for the Bookshelf service, over the data of the lab. The data differs by path (metrics arrive over OTLP in the default lab; the PromQL column assumes the Prometheus metrics are also written by remote write), so the field and metric names are conventions to adapt, not guaranteed fields.

Question KQL (filter) ES|QL PromQL

Rate

service.name : "bookshelf", then count in Discover

The TS query above: COUNT of the request histogram by TBUCKET

sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))

Errors

service.name : "bookshelf" and severity_text : "ERROR"

The STATS errors = COUNT(*) WHERE ... query above, divided by total

sum(rate(http_server_requests_seconds_count{application="bookshelf",status=~"5.."}[5m])) / sum(rate(http_server_requests_seconds_count{application="bookshelf"}[5m]))

Duration

Not applicable: KQL cannot aggregate

PERCENTILE(http.server.requests, 95) in the TS example

histogram_quantile(0.95, sum by (le) (rate(http_server_requests_seconds_bucket{application="bookshelf"}[5m])))

The practical rule: use KQL to narrow, ES|QL when the answer is a table or a chart you may later join or reshape, and PromQL when the query already exists as PromQL or the team thinks in it. The same expressions turn into rules in Observability Rules and Universal Alerting & Watcher, and into Lens formulas on Lens.

Verify it in the lab

  1. Start the kibana profile and the load generator, then open Discover with the bookshelf-logs data view of Data Views & Discover.

  2. Enter the KQL filter above and confirm that only Bookshelf error documents remain; add or without parentheses next to and and compare the result with a parenthesised version to see the precedence rule.

  3. Switch to ES|QL mode and run the STATS ... BUCKET query. Remove TO_DOUBLE and observe an error_share of 0 in every bucket.

  4. Run the TS query. If it fails on a field name, open the metrics grid, read the real field names and adjust.

  5. Create the bookshelf-routes index and a few documents (url.path and owner), run the LOOKUP JOIN query and add a second document with the same url.path to see the row duplication.

  6. If Prometheus remote write is enabled (see the ingest page), run the PROMQL query and compare its rate with the TS rate.

  7. Add SET approximation=true; in front of the 30-day query and note the bolt badge and the interval column.

What can go wrong

  • Integer division. COUNT is an integer: convert before dividing.

  • Wrong precedence. KQL pasted into KQL() groups differently; parenthesise.

  • Leading wildcards. Slow on large data, and the setting is not available on Serverless.

  • FROM over counters. Summing a counter field with FROM | STATS ignores resets; use TS and RATE.

  • Gauge treated as counter. RATE rejects a gauge, and on the Prometheus path a counter without a recognised suffix is stored as a gauge.

  • PromQL gaps. A query using an unsupported construct is rejected with an error, not silently different; read the compatibility page before porting a dashboard.

  • Approximate alerts. Sampling in a rule query makes the threshold flap; keep rules exact.

  • Time zone drift. A rule bucketing by day runs in UTC while Discover shows the browser or dateFormat:tz zone.

In the books

Shah’s Kibana 8.x Quick Start Guide (chapter 9) introduces ES|QL as it was in Elasticsearch 8.11: commands joined by pipes, FROM, WHERE, STATS ... BY and ENRICH, with the SQL comparison. The language has grown since: TS, PROMQL, LOOKUP JOIN, TBUCKET, approximation and SET directives did not exist, and the chapter contains statements that do not match the current reference, such as keywords being case-sensitive (the reference says they are case-insensitive), so check each query against the official ES|QL reference before using it.

Where to go next