Elasticsearch Esql
ElasticOfficialCreated by elastic
- Skill
- Tool integration
- Data and AI
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured approach to executing ES|QL (Elasticsearch Query Language) queries against Elasticsearch deployments. It guides users through verifying cluster connectivity, discovering index schemas, and generating piped queries for data analysis, log exploration, and metric aggregation. The skill emphasizes version-aware query generation, ensuring that features are used only when compatible with the target cluster, and provides fallback patterns for older environments.
What it does
- Verifies cluster connectivity and detects deployment type (Stack vs. Serverless).
- Discovers index schemas and field types to ensure accurate query generation.
- Generates ES|QL queries using piped commands for filtering, transformation, and aggregation.
- Provides version-specific guidance and fallback patterns for advanced ES|QL features.
- Supports time series data analysis using specialized TS commands and TBUCKET functions.
- Executes queries via the elastic CLI and returns results in a tabular format.
When to use it
- When you need to perform ad-hoc analysis or log exploration on Elasticsearch data.
- When you want to aggregate metrics or create time-series visualizations.
- When you need to transform data using piped operations like EVAL, STATS, and SORT.
- When you are migrating from legacy Query DSL to the piped ES|QL syntax.
Advantages
- Ensures query accuracy by mandating schema discovery before generation.
- Prevents compatibility errors by checking cluster version against feature availability.
- Provides standardized fallback patterns for environments lacking newer features.
- Promotes clean, readable query structures using the piped ES|QL paradigm.
Usage examples
- “Show me the top 10 error logs from the last 24 hours.”
- The agent discovers the relevant index, generates an ES|QL query using FROM, WHERE, and LIMIT, and executes it via the elastic CLI.
- “Calculate the average CPU usage per hour for my metrics index.”
- The agent identifies the index as a time series, uses the TS command with TBUCKET, and returns the aggregated hourly averages.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/elastic/elasticsearch-esql/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip elasticsearch-esql.zip -d .agents/skills
Documentation by elastic
Elasticsearch ES|QL
Execute ES|QL queries against Elasticsearch: discover the schema, choose the right ES|QL feature for the task, generate the simplest correct query, and run it.
<!-- begin-partial: preamble -->
Environment Configuration
This skill executes Elasticsearch operations through the elastic CLI. If the
elastic CLI is not installed, tell the user what it is needed for. Do
not guess credentials, call the HTTP API directly, or attempt other workarounds.
This skill references operations in HTTP-shorthand form (e.g., GET /, GET /_cat/indices, GET /{index}/_mapping,
GET /{index}/_settings/index.mode, POST /_query). The Operations table at the end of this document
maps each shorthand to the equivalent elastic CLI command — always use the CLI rather than calling the HTTP API
directly.
<!-- end-partial: preamble -->
What is ES|QL?
ES|QL (Elasticsearch Query Language) is a piped query language for Elasticsearch. It is NOT the same as:
Elasticsearch Query DSL (JSON-based)
SQL
EQL (Event Query Language)
ES|QL uses pipes (|) to chain commands:
FROM index | WHERE condition | STATS aggregation BY field | SORT field | LIMIT n
Prerequisite: ES|QL requires
_sourceto be enabled on queried indices. Indices with_sourcedisabled (e.g.,"_source": { "enabled": false }) will cause ES|QL queries to fail.Version Compatibility: ES|QL was introduced in 8.11 (tech preview) and became GA in 8.14. Features like
LOOKUP JOIN(8.18+),MATCH(8.17+), andINLINE STATS(9.2+) were added in later versions. On pre-8.18 clusters, useENRICHas a fallback forLOOKUP JOIN(see generation tips).INLINE STATSand counter-fieldRATE()have no fallback before 9.2. Check references/esql-version-history.md for feature availability by version.Cluster Detection: Call
GET /to determine the cluster type and version:
build_flavor: "serverless"— Elastic Cloud Serverless.version.numbertracks the stack line under active development (next minor from main), so clients that only semver-compare may treat Serverless as “latest.” Do not useversion.numberto gate features: ifbuild_flavoris"serverless", assume all GA and preview ES|QL features are available.
build_flavor: "default"— Stack (self-managed or Cloud-hosted). Useversion.numberfor feature availability.Snapshot builds have
version.numberlike9.4.0-SNAPSHOT. Strip the-SNAPSHOTsuffix and use the major.minor for version checks. Snapshot builds include all features from that version plus potentially unreleased features from development — if a query fails with an unknown function/command, it may simply not have landed yet. Elastic employees commonly use snapshot builds for testing.
Process
Verify the connection and detect the deployment type. Call
GET /first. This confirms connectivity and detects whether the deployment is a Serverless project (all features available) or a versioned cluster (features depend on version). Thebuild_flavorfield is the authoritative signal — if it equals"serverless", ignore the reported version number and use all ES|QL features freely. If the call fails, stop and point the user at the CLI configuration instructions rather than guessing endpoints or credentials.Discover the schema (required — never guess index or field names). List candidate indices with
GET /_cat/indices(pass a pattern to narrow), then fetch field types for the chosen index withGET /{index}/_mapping.Always run schema discovery before generating queries. Index names and field names vary across deployments and cannot be reliably guessed. Even common-sounding data (e.g., "logs") may live in indices named
logs-test,logs-app-*, orapplication_logs. Field names may use ECS dotted notation (source.ip,service.name) or flat custom names — the only way to know is to check.Prefer simplicity: Query a single index unless the user explicitly asks for data across multiple sources. Do not combine indices with different schemas using
COALESCEunless specifically requested — pick the single most relevant index for the question. When multiple indices contain similar data, prefer the one with the most complete schema for the task at hand.Detect time series indices. Check the index mode with
GET /{index}/_settings/index.mode. If it istime_series, useTS <data-stream>(notFROM),TBUCKET(interval)(notDATE_TRUNC), and wrap counter fields withSUM(RATE(...)). Read the full TS section in Generation Tips before writing any time series query. For TSDS indices on 9.4+, prefer the in-language discovery commandsMETRICS_INFOandTS_INFO(both GA) over inspecting mappings — they enumerate the metric catalogue and the dimension labels of each time series directly, and are run as ES|QL queries viaPOST /_query. TreatMETRICS_INFOas authoritative formetric_type(counter/gauge/histogram) andfield_type(histogram,tdigest,exponential_histogramfor distribution metrics). Both must followTSand must precedeSTATS/SORT/LIMIT. See Time Series Queries:TS metrics-tsds | METRICS_INFO | SORT metric_name TS metrics-tsds | TS_INFO | KEEP metric_name, dimensions | SORT metric_nameChoose the right ES|QL feature for the task. Version gate (mandatory on Stack): before writing any query, compare
version.numberto the version tag of every command and function you plan to use. For each feature newer than the cluster (for example a 9.5 feature on 9.4), use its fallback from the table below or tell the user it is unavailable on their version — never emit it, and never silently drop the part of the question it answers. Serverless has every released GA and preview feature. Then match the user's intent to the most appropriate ES|QL feature, preferring a single advanced query over multiple basic ones:"find patterns," "categorize," "group similar messages" →
CATEGORIZE(field)"spike," "dip," "anomaly," "when did X change" →
CHANGE_POINT value ON key"trend over time," "time series" →
STATS ... BY BUCKET(@timestamp, interval)orTSfor TSDB"PromQL", "Prometheus query/dashboard/alert",
sum by (instance) (...), label matchers like{cluster="prod"}→PROMQLsource command (GA in 9.5+/Serverless, preview in 9.4); see PROMQL Command. PreferTSfor native ES|QL phrasing."search," "find documents matching" →
MATCH(default),QSTR(advanced boolean),KQL(Kibana migration). For content/document relevance search, follow the ES|QL Search Strategy"count," "average," "breakdown" →
STATSwith aggregation functions"approximate," "estimate," "rough numbers," "fast/cheap stats on huge data" →
SET approximation=true;before aSTATSquery (GA in 9.5+/Serverless, preview in 9.4); see Query Approximation"random sample," "random subset of rows" →
| SAMPLE 0.1(row probability; preview 8.19/9.1, GA 9.5), thenLIMIT nif a row count is asked; there is noRANDOM()function"latest/first value per group," "most recent status per host" →
STATS LAST(field, @timestamp) BY group(orFIRST), notSORT+LIMIT 1allow list, deny list, "exclude known IPs/users" from another index →
WHERE field [NOT] IN (FROM idx | KEEP col)(preview 9.5); useLOOKUP JOINonly when you need the other index's columns"unique combinations," "no duplicates" →
STATS BY a, b; Serverless only:KEEP a, b | DEDUP(preview)IPs mapped as
keyword→ convert withTO_IP()beforeCIDR_MATCH, IP comparisons,IN (FROM …), orLOOKUP JOINon anipfield; for the last twoEVAL ip = TO_IP(src)first (the left side must be a column)"country/city of an IP," "geolocate IPs," ASN →
| IP_LOCATION geo = ip_fieldpipe command (preview 9.5)parse URLs (domain, path, query) →
| URI_PARTS parts = url_fieldpipe command (preview 9.4), notDISSECT/GROK"in my local time," "per day in New York" →
SET time_zone = "America/New_York";(9.4+), not manual offsetsflattenedfield sub-keys (e.g. OTelresource.attributes) →FIELD_EXTRACT(field, "host.name")(preview 9.5), notfield.host.name; it returnskeyword, so cast (TO_INTEGER(...)) before numeric comparisonsembed text/images at query time for vector search →
EMBEDDING(value, inference_id)(preview 9.5) orTEXT_EMBEDDING(text, inference_id)insideKNNquery files in S3 (Parquet/CSV/NDJSON) without ingesting, or a named federated dataset →
FROM <dataset>via Data Federation (experimental 9.5, not for production; ECH and self-managed only, not Serverless); only when asked, and warn
9.5 or Serverless-only feature Fallback on Stack without the feature DEDUP(Serverless preview only)LIMIT 1 BY cols(9.4+;SORTfirst picks the kept row) orSTATS BY colsWHERE x NOT IN (FROM idx | KEEP c)LOOKUP JOIN idx ON x == c | WHERE c IS NULL(IN:IS NOT NULL);ONexpressions need 9.2+, elseRENAME x AS cfirstIP_LOCATIONNo query-time GeoIP: ENRICHwith an IP-range enrich policy, or the ingestgeoipprocessorFIELD_EXTRACT(or an unmapped key)FROM idx METADATA _source | EVAL v = JSON_EXTRACT(_source, "$.labels.key")— notlabels.key,labels["key"], orJSON_EXTRACT(labels, …);COALESCEwith"$.labels[\"k.sub\"]"for pre-dotted keysRead only the reference for the feature you need before generating the query (the bold "read before" ones are mandatory for their feature). Do not read every reference up front; open another only if the query fails:
Generation Tips - key patterns (TS/TBUCKET/RATE, per-agg WHERE, LOOKUP JOIN, CIDR_MATCH), common templates, and ambiguity handling
Time Series Queries - read before any TS query: inner/outer aggregation model, TBUCKET syntax, RATE constraints, histogram metrics
PROMQL Command — read before any PROMQL query: options, output schema, handling unsupported PromQL, and
PROMQLvsTSdecision matrix (GA in 9.5+/Serverless, preview in 9.4)ES|QL Complete Reference - full syntax for all commands and functions
ES|QL Search Strategy — for content/document relevance search (retrieve → fuse → rerank)
ES|QL Search Reference — for full-text search function syntax (MATCH, QSTR, KQL, scoring)
Query Approximation — read before using
SET approximation: output columns, sampling/confidence-level tuning, unsupported functions and patterns (GA in 9.5+/Serverless, preview in 9.4)
Generate the query following ES|QL syntax. Prefer the simplest query that answers the question — do not add extra indices, fields, or transformations unless the user asks for them. Only include fields in
KEEPthat directly answer the question. Do not add extra filter conditions beyond what the user specified (e.g., don't addOR level == "ERROR"when the user just said "errors").Start with
FROM index-pattern(orTS index-patternfor time series indices)Add
WHEREfor filtering (useTRANGEfor time ranges on 9.3+)Use
EVALfor computed fieldsUse
STATS ... BYfor aggregationsFor time series metrics:
TSwithSUM(RATE(...))for counters,AVG(...)for gauges, standard aggregations (SUM,AVG,PERCENTILE, … — not*_OVER_TIME) for histogram metrics, andTBUCKET(interval)for time bucketing — see the TS section in Generation Tips and Histogram MetricsFor detecting spikes, dips, or anomalies, use
CHANGE_POINTafter time-bucketed aggregationAdd
SORTandLIMITas neededRe-check the version gate before answering: on Stack 9.4 or earlier the query must not contain
IN (FROM,IP_LOCATION,FIELD_EXTRACT, or any other 9.5 feature, and on any Stack noDEDUP— rewrite with the fallback.
Execute the query with
POST /_query. Request tabular (TSV) output for clean, decoration-free results that are easy to read and post-process.
ES|QL Quick Reference
Version availability: This section omits version annotations for readability. Check ES|QL Version History for feature availability by Elasticsearch version.
Basic Structure
FROM index-pattern
| WHERE condition
| EVAL new_field = expression
| STATS aggregation BY grouping
| SORT field DESC
| LIMIT nCommon Patterns
Filter and limit:
FROM logs-*
| WHERE @timestamp > NOW() - 24 hours AND level == "error"
| SORT @timestamp DESC
| LIMIT 100Aggregate by time: For time series (TSDS) indices, prefer TS with TRANGE and TBUCKET over FROM +
DATE_TRUNC (see the time series section below).
TS metrics-*
| WHERE TRANGE(7 days)
| STATS avg_cpu = AVG(cpu.percent) BY bucket = TBUCKET(1 hour)
| SORT bucket DESCTop N with count:
FROM web-logs
| STATS count = COUNT(*) BY response.status_code
| SORT count DESC
| LIMIT 10Text search (8.17+): Use MATCH as the default for full-text search instead of LIKE/RLIKE — it is significantly
faster and supports relevance scoring. MATCH on a text field is usually sufficient on its own — do not add redundant
keyword equality filters (e.g., category == "X") alongside MATCH unless the user explicitly requests filtering. Use
QSTR only when you need advanced boolean logic, wildcards, or multi-field searches in a single expression. The first
argument to MATCH must be one real field name — not a string listing several fields (e.g. "title,content") and
not multiple field arguments; combine fields with MATCH(a, "q") OR MATCH(b, "q"). KQL is available from 8.18/9.0+.
For content/document search use cases, follow the ES|QL Search Strategy. See
ES|QL Search Reference for the full function guide.
FROM documents METADATA _score
| WHERE MATCH(content, "search terms")
| SORT _score DESC
| LIMIT 20String extraction: Use DISSECT for structured delimiter-based patterns (preferred — produces named fields) and
GROK for regex-based extraction. For simple cases, SUBSTRING(s, start, len) for fixed-position extraction,
SPLIT(s, delim) to split into a multivalue, LOCATE(substr, s) to find a character position. SPLIT returns a
multivalue — use MV_FIRST, MV_LAST, or MV_SLICE to pick elements. INSTR and STRPOS do not exist — use
LOCATE. REGEXP_EXTRACT does not exist — use GROK.
// Extract domain from email using DISSECT (preferred — produces named fields)
FROM customers
| DISSECT email "%{local}@%{domain}"
| STATS count = COUNT(*) BY domain
// Alternative: extract domain from email using SPLIT
FROM customers
| EVAL domain = MV_LAST(SPLIT(email, "@"))
| STATS count = COUNT(*) BY domainLog categorization (Platinum license): Use CATEGORIZE to auto-cluster log messages into pattern groups. Prefer
this over running multiple STATS ... BY field queries when exploring or finding patterns in unstructured text.
CATEGORIZE(field) must be the first grouping key in STATS ... BY — any other grouping (a time bucket, a service
name) has to come after it: BY category = CATEGORIZE(message), bucket = BUCKET(@timestamp, 1 hour), never the reverse
(it fails to parse).
FROM logs-*
| WHERE @timestamp > NOW() - 24 hours
| STATS count = COUNT(*) BY category = CATEGORIZE(message)
| SORT count DESC
| LIMIT 20Change point detection (Platinum license): Use CHANGE_POINT to detect spikes, dips, and trend shifts in a metric
series. Prefer this over manual inspection of time-bucketed counts.
FROM logs-*
| STATS c = COUNT(*) BY t = BUCKET(@timestamp, 30 seconds)
| SORT t
| CHANGE_POINT c ON t
| WHERE type IS NOT NULLTime series metrics: With TS, use TRANGE for time filtering (9.3+) or omit it entirely — do not add a
redundant WHERE @timestamp > NOW() - ... alongside TBUCKET. The TBUCKET duration defines the aggregation window.
// Counter metric: SUM(RATE(...)) with TBUCKET(duration)
TS metrics-tsds
| WHERE TRANGE(1 hour)
| STATS SUM(RATE(requests)) BY TBUCKET(1 hour), host
// Gauge metric: AVG(...) — no RATE needed
TS metrics-tsds
| STATS avg_cpu = AVG(cpu) BY service.name, bucket = TBUCKET(5 minutes)
| SORT bucket
// Histogram metric: standard aggregation (merge); cast for wildcard/mixed streams
TS metrics-*
| STATS total_gc = SUM(jvm.gc.duration::exponential_histogram) BY TBUCKET(1 hour), service.nameTime series with PromQL syntax (GA in 9.5+/Serverless, preview in 9.4): Use the PROMQL source command when the
user explicitly asks for PromQL, references Prometheus syntax (sum by (instance) (...), label matchers like
{cluster="prod"}), or is migrating a Prometheus dashboard or alert. Otherwise prefer TS. Its output flows into the
rest of the ES|QL pipeline; the time column is step, and there is no @timestamp column. Not every PromQL construct
is supported yet. Read PROMQL Command before writing a PROMQL query: it mirrors the
Elasticsearch docs, including best practices, single-value results, and the unsupported constructs.
// Adaptive Kibana query — date picker drives time range and step
PROMQL index=metrics-* http_rate=(sum(rate(http_requests_total)))
// (9.5+; Serverless) Current value for a metric or gauge panel — instant query at the end of the date picker range
PROMQL index=metrics-* time=?_tend load=(avg(node_load1))
// Named result, post-processed with ES|QL
PROMQL index=k8s step=1h bytes=(max by (cluster) (network.bytes_in))
| STATS max_bytes = MAX(bytes) BY cluster
| SORT clusterData enrichment with LOOKUP JOIN: The basic ON clause matches fields by name in both indices
(LOOKUP JOIN idx ON field_name). When the join key has a different name in the source, use RENAME first to align
names. 9.2+ tech preview also supports expression predicates (ON expr == expr); see
ES|QL Complete Reference for details. After LOOKUP JOIN, lookup columns are available
by their original field names — do not table-qualify them (e.g., write threat_level, not
threat_intel.threat_level). Ordering tip: when the question asks for top-N results, SORT and LIMIT before
LOOKUP JOIN to reduce enrichment cost. For general listings or full enrichment, place LOOKUP JOIN right after
FROM/WHERE.
// Field name mismatch — RENAME before joining
FROM support_tickets
| RENAME product AS product_name
| LOOKUP JOIN knowledge_base ON product_name
// Aggregate, limit, THEN enrich (top-N only)
FROM orders
| STATS total_spent = SUM(total) BY customer_id
| SORT total_spent DESC
| LIMIT 3
| LOOKUP JOIN customers_lookup ON customer_id
| KEEP name, customer_id, total_spent
// Multi-field join (9.2+)
FROM application_logs
| LOOKUP JOIN service_registry ON service_name, environment
| KEEP service_name, environment, owner_teamMultivalue field filtering: Use MV_CONTAINS to check if a multivalue field contains a specific value. Use
MV_COUNT to count values.
// Filter by multivalue membership
FROM employees
| WHERE MV_CONTAINS(languages, "Python")
// Find entries matching multiple values
FROM employees
| WHERE MV_CONTAINS(languages, "Java") AND MV_CONTAINS(languages, "Python")
// Count multivalue entries
FROM employees
| EVAL num_languages = MV_COUNT(languages)
| SORT num_languages DESCChange point detection (alternate example): Use when the user asks about spikes, dips, or anomalies. Requires
time-bucketed aggregation, SORT, then CHANGE_POINT.
FROM logs-*
| STATS error_count = COUNT(*) BY bucket = DATE_TRUNC(1 hour, @timestamp)
| SORT bucket
| CHANGE_POINT error_count ON bucket AS type, pvalueApproximate STATS (GA in 9.5+/Serverless, preview in 9.4): Prepend SET approximation=true; to a STATS query to
get fast estimates via sampling and extrapolation on large datasets when exact values are not required. The result adds
_approximation_confidence_interval(col) and _approximation_certified(col) columns per estimated quantity — report
those bounds, do not present estimates as exact. COUNT_DISTINCT, MIN, MAX, FIRST, LAST, TOP (and a few
others) are not supported and fall back to exact execution; use the SAMPLE command for those. Pipelines with 2+
STATS, or using the TS/PROMQL source command, also fall back. To tune it, pass a map instead of true:
SET approximation={"confidence_level":0.95}; or SET approximation={"rows":N}; (N ≥ 10,000), or both in one map —
never SET approximation=true, confidence_level=0.95;. See Query Approximation.
SET approximation=true;
FROM web_traffic
| WHERE @timestamp >= NOW() - 1 week
| STATS total_hits = COUNT(*), avg_load_time = AVG(page_load_ms) BY country_code
| SORT total_hits DESC
| LIMIT 5Full Reference
For complete ES|QL syntax including all commands, functions, and operators, read:
ES|QL Search Reference - Full-text search: MATCH, QSTR, KQL, MATCH_PHRASE, scoring, semantic search
ES|QL Search Strategy - Relevance search strategy for content indices: retrieve → fuse → rerank
ES|QL Version History - Feature availability by Elasticsearch version
Query Patterns - Natural language to ES|QL translation
Generation Tips - Best practices for query generation
Time Series Queries - TS command, time series aggregation functions, TBUCKET
PROMQL Command - PromQL source command for TSDS indices (GA in 9.5+/Serverless, preview in 9.4)
Query Approximation - Approximate STATS via sampling/extrapolation (GA in 9.5+/Serverless, preview in 9.4)
DSL to ES|QL Migration - Convert Query DSL to ES|QL
Error Handling
When query execution fails, read the error message from Elasticsearch and correct the query. Common issues:
Field doesn't exist → Always inspect the mapping (
GET /{index}/_mapping) and list indices (GET /_cat/indices) before writing a query. Never guess field or index names — they vary across deployments.Type mismatch → Use type conversion functions (TO_STRING, TO_INTEGER, etc.)
Syntax error → Review ES|QL reference for correct syntax. Always use double quotes for strings, never single quotes.
Reserved keywords → Never use
first,last,by,in,is,on,with(orand,or,not,like,rlike,null,true,false,asc,desc,nulls) bare as a column name or dotted segment. Rename aliases (first_seen) or backquote real field names. InsideFUSE, backquote a column namedscore,keyorgroupafterSCORE BY/KEY BY/GROUP BY. Backquoting any identifier always works; on an unexplained parse error on a name, backquote it. See Generation Tips.No results → Check time range and filter conditions
Wrong function name → ES|QL uses underscored names:
STD_DEV()notSTDDEV(),MEDIAN_ABSOLUTE_DEVIATION()notMAD(). UseCONCAT()for strings, not+. UseCASE(cond, val, ...)notCASE WHEN...THEN...END.Wrong date part →
DATE_EXTRACTuses ES|QL part names:"hour_of_day"not"hour","day_of_month"not"day","month_of_year"not"month". UseDATE_DIFF("day", start, end)for date arithmetic, not subtraction.
Examples
Each example follows the process: inspect the mapping first, then write the simplest correct query.
"Top 10 source IPs by request count in the last hour" — filter by time window, then aggregate and rank:
FROM logs-*
| WHERE @timestamp > NOW() - 1 hour
| STATS requests = COUNT(*) BY source.ip
| SORT requests DESC
| LIMIT 10"Average response time per service, only for 5xx responses" — filter to errors before aggregating:
FROM traces-*
| WHERE http.response.status_code >= 500
| STATS avg_ms = AVG(duration_ms) BY service.name
| SORT avg_ms DESC"Error count per day for the last week" — bucket by day with DATE_TRUNC:
FROM logs-*
| WHERE log.level == "error" AND @timestamp > NOW() - 7 days
| STATS errors = COUNT(*) BY day = DATE_TRUNC(1 day, @timestamp)
| SORT day ASCGuidelines
Inspect before querying. Read the mapping (
GET /{index}/_mapping) and list indices (GET /_cat/indices) before writing a query — never guess field or index names.Filter early. Put
WHEREbeforeSTATSso aggregation runs over the smallest row set.Always bound results. End exploratory queries with
LIMIT.Quote correctly. Use double quotes for string literals, never single quotes.
Respect version gating. Confirm feature availability with
GET /(build_flavor,version.number) and references/esql-version-history.md before using newer commands such asLOOKUP JOINorINLINE STATS.Correct on error, do not guess. Read the Elasticsearch error, fix the specific issue, and re-run.
Operations
| HTTP API (shorthand) | elastic CLI command |
|---|---|
GET / | elastic es info |
GET /_cat/indices | elastic es cat indices --index '<pattern>' |
GET /{index}/_mapping | elastic es indices get-mapping --index '<index>' |
GET /{index}/_settings/index.mode | elastic es indices get-settings --index '<index>' --name index.mode |
GET /_resolve/index/{name} | elastic es indices resolve-index --name '<name>' |
POST /_query | elastic es esql query --format tsv --query "<esql>" |
Files
- ATTRIBUTION.mdAdded by AutoGineer977 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md28.3 KiB
- references/dsl-to-esql-migration.md38.5 KiB
- references/esql-reference.md100.8 KiB
- references/esql-search-strategy.md10.6 KiB
- references/esql-search.md26.3 KiB
- references/esql-version-history.md46.4 KiB
- references/generation-tips.md31.9 KiB
- references/promql-command.md26.0 KiB
- references/query-approximation.md11.2 KiB
- references/query-patterns.md14.7 KiB
- references/time-series-queries.md31.3 KiB
references/promql-command.md
ES|QL PROMQL Command
Query time series indices using Prometheus Query Language (PromQL) as a source command in ES|QL. The PROMQL
command is the bridge for users who already know PromQL or are migrating Prometheus dashboards and alerts onto an
Elasticsearch backend, while still letting them post-process results with regular ES|QL pipes.
Table of Contents
From the Elasticsearch docs:
Syntax
Options
Time range
Output columns
Index patterns
Implicit range selectors
Time range durations
Best practices
Limitations
Examples
Skill guidance:
When to Use PROMQL
Running PROMQL Queries
Handling Unsupported Constructs
Stack 9.4 and 9.5 fallbacks
Kibana Charts
Guidelines
References
<!-- Everything between begin-docs and end-docs mirrors the PROMQL command page of the Elasticsearch docs (https://www.elastic.co/docs/reference/query-languages/esql/commands/promql). Don't edit it here: change the docs instead, then copy the page again. Version badges are kept, shortened to the notation used in this skill: bare versions refer to the Elastic Stack, generally available is implied, and other lifecycles are spelled out, such as `(9.5+; Serverless)` or `(9.4 only, preview)`. Everything after end-docs is specific to this skill. -->
<!-- begin-docs: esql/commands/promql -->
Availability: 9.5+, preview in 9.4; Serverless
The PROMQL source command queries
time series indices
using Prometheus Query Language (PromQL). Like
TS, it enables time series aggregation
functions, but accepts PromQL syntax instead of ES|QL.
Note
PROMQLsupports most, but not all, of PromQL. Refer to Limitations for unsupported constructs, to PromQL limitations for behavioral differences from Prometheus, and to PromQL functions for the supported functions and their restrictions.
Syntax
The PROMQL command accepts zero or more space-separated <option>=<value> pairs, followed by a PromQL expression in
parentheses that can be prefixed with a result name.
PROMQL [ <option>=<value> ... ] [ <result_name>= ](<PromQL Expression>)Options
The options are inspired by the Prometheus HTTP API with some additions specific to ES|QL.
index: A list of indices, data streams, or aliases. Supports wildcards and date math. Defaults tometrics-*querying matching indices withindex.mode: time_series. Example:PROMQL index=metrics-*.otel-* http_rate=(sum(rate(http_requests_total)))step: Query resolution step width (optional). Automatically determined given the number of targetbucketsand the selected time range. Example:PROMQL step=1m http_rate=(sum(rate(http_requests_total)))buckets: Target number of buckets for auto-step derivation. Defaults to100. Mutually exclusive withstep. Requires a known time range, either by settingstartandendexplicitly or implicitly through Kibana's time range filter. Example:PROMQL buckets=50 start="2026-04-01T00:00:00Z" end="2026-04-01T01:00:00Z" http_rate=(sum(rate(http_requests_total)))start: Start time of the query, inclusive (optional). Uses the start based on Kibana's date picker if missing. Set together withend. Refer to Time range for queries without a time range. Example:PROMQL start="2026-04-01T00:00:00Z" end="2026-04-01T01:00:00Z" http_rate=(sum(rate(http_requests_total)))end: End time of the query, inclusive (optional). Uses the end based on Kibana's date picker if missing. Set together withstart, and not before it. Refer to Time range for queries without a time range. Example:PROMQL start="2026-04-01T00:00:00Z" end="2026-04-01T02:00:00Z" http_rate=(sum(rate(http_requests_total)))time: (9.5+; Serverless) Evaluation time of an instant query (optional). Evaluates the expression once, at this time, instead of at each step of a range query. Mutually exclusive withstart,end,step, andbuckets. Example:PROMQL time="2026-04-01T01:00:00Z" http_rate=(sum(rate(http_requests_total)))scrape_interval: The expected metric collection interval. Defaults to1m. Used to determine implicit range selector windows asmax(step, scrape_interval). Example:PROMQL scrape_interval=15s http_rate=(sum(rate(http_requests_total)))<result_name>=(<PromQL Expression>): Name of the output column with the query result timeseries (optional). By default, the name of the output column is the PromQL expression itself. Example:PROMQL http_rate=(sum by (instance) (rate(http_requests_total))) | SORT http_rate DESC
start, end, and time accept an RFC 3339 timestamp with a UTC offset, such as "2026-04-01T00:00:00Z", or a Unix
timestamp in seconds, which can be fractional, such as 1775001600. Date math, such as now-1h, isn't supported. In
Kibana, the ?_tstart and ?_tend parameters reference the time range of the date picker, such as time=?_tend.
step and scrape_interval accept a PromQL duration, such as 30s or 5m, or a number of seconds.
Description
The PROMQL command takes standard PromQL parameters and a PromQL expression, runs the query, and returns the results
as regular ES|QL columns. You can continue to process the columns with other ES|QL commands.
Time range
A range query needs either step, or both start and end, from which the step is derived using buckets. In Kibana,
the date picker provides start and end. Without a time range and without step, the query fails. With step but no
time range, the query covers all data in the index.
Output columns
The result contains the following columns:
| Column | Type | Description |
|---|---|---|
The PromQL expression (or <result_name> if specified) | double | The computed metric value |
step | date | The timestamp for each evaluation step. For an instant query, the evaluation time |
| Grouping labels (if any) | keyword | One column per grouping label from by clauses |
_timeseries (if any) | keyword | The labels of each series as a JSON string |
The label columns depend on the outermost aggregation of the PromQL expression:
With a
bygrouping, such assum by (instance) (...), each grouping label gets its own output column.With an aggregation without grouping, such as
sum(...), there are no label columns, and the result is a single series.Without a cross-series aggregation, such as
rate(http_requests_total), or with awithoutgrouping, such assum without (pod) (...), the remaining labels of each series are returned in a single_timeseriescolumn as a JSON string.
A range query returns one row per series and evaluation step. An instant query returns one row per series.
Index patterns
The index parameter accepts the same patterns as FROM and TS, including wildcards and comma-separated lists. If
omitted, it defaults to metrics-*, which queries matching indices configured with
index.mode: time_series.
The Prometheus-compatible query and query_range endpoints use the same default when the {index} path parameter is
omitted.
Implicit range selectors
In standard PromQL, functions like rate require a range selector: rate(http_requests_total[5m]). The PROMQL
command allows omitting the range selector entirely. When the range selector is absent, the window is determined
automatically as max(step, scrape_interval). For example:
PROMQL scrape_interval=15s http_rate=(sum(rate(http_requests_total))). An implicit window adapts to the time range and
step. A fixed window doesn't: when it's shorter than the step, such as [5m] with a step of 1h, each step only
reflects the last 5 minutes and ignores the samples in between. A fixed window is only useful when you need exactly that
window, such as the rate over the last 5 minutes.
Time range durations
(Serverless) A duration, such as in a range selector, can be the difference of two RFC 3339 timestamp parameters. For
example, [?_tend - ?_tstart] spans the time range of the date picker in Kibana.
Best practices
Set
indexexplicitly instead of relying on themetrics-*default, to narrow the data scanned.Omit range selectors, also when porting a Prometheus query: write
rate(http_requests_total)instead ofrate(http_requests_total[5m]), so the window adapts to the time range and step. Refer to Implicit range selectors. The exception is a value over the whole time range. Refer to Single-value results.Name the result, such as
http_rate=(...). Otherwise, the value column is named after the expression text, which changes whenever the expression is reformatted, so later commands can't reliably reference it.Match the function to the metric type: use
rate,irate, orincreasefor counters, and functions such asavg_over_timeormax_over_time, or the raw metric, for gauges. For native histograms, useincreaseinstead ofrate, and wrap the result in a histogram function, such ashistogram_quantile(0.99, sum by (job) (increase(http_request_duration_seconds))).In Kibana, omit
startandendso the query follows the date picker. Elsewhere, setstartandendexplicitly, rather than onlystep, which covers all data in the index.Filter by labels in the PromQL selector, such as
network.cost{cluster!="prod"}, rather than withWHEREafterPROMQL. Selector filters reduce the data read, and a laterWHEREdoesn't.
Single-value results
A range query returns a value for every step. To get a single value per series, such as for a metric or gauge chart or a
ranking, use an instant query. In Kibana, set time=?_tend to evaluate the expression at the end of
the time range of the date picker (refer to
time range parameters).
For the current value, such as the current request rate, omit the range selector:
PROMQL index=metrics-generic.prometheus-* time=?_tend http_rate=(sum(rate(http_requests_total)))For a value over the whole time range, such as the total number of requests, use a range selector that spans the time range,
[?_tend - ?_tstart](Serverless):PROMQL index=metrics-generic.prometheus-* time=?_tend total_requests=(sum(increase(http_requests_total[?_tend - ?_tstart])))This is also how to port a Grafana query that uses the
$__rangevariable, or its$__range_sand$__range_msvariants: replace the range selector, such as[$__range]or[${__range_s}s], with[?_tend - ?_tstart], and settime=?_tend. Refer to Time range durations.
Limitations
The majority of PromQL expressions run unchanged. The following constructs are not evaluated yet, so they return a client error (4xx):
Binary set operators:
andandunless.(Serverless) Binary set operator
or, except at the top level of an expression. A top-levelorchain supports at most 8 operands by default (esql.query.max_branch_count_per_merge) and can't useon(...)orignoring(...). A nestedor, a chain that exceeds that limit, or anorwithon(...)orignoring(...)returns a client error (4xx).(9.5 only) Binary set operator
or, except at the top level of an expression. A top-levelorchain supports at most 8 operands and can't useon(...)orignoring(...). A nestedor, a chain of more than 8 operands, or anorwithon(...)orignoring(...)returns a client error (4xx).Comparison operators: evaluated only at the top level of an expression and only with a scalar literal on the right-hand side. Comparisons between two instant vectors, and nested comparisons, return a client error (4xx).
Group modifiers:
on(...),ignoring(...),group_left,group_right.The
@modifier.Subqueries, such as
max_over_time(rate(http_requests_total)[1h:]).Selectors without a metric name, and regex matchers on
__name__, such as{__name__=~"node_.*"}.Binary expressions with a
without(...)aggregation as an operand, andwithout(...)aggregations nested inside anotherwithout(...)aggregation, such assum without (pod) (max without (container) (...)). Useby(...)instead.(9.5+; Serverless) Binary expressions whose operands use different
offsetvalues, such asrate(http_requests_total) / rate(http_requests_total offset 1h). This restriction doesn't apply toor.(9.5+; Serverless) Binary expressions where both operands read metrics and one of them nests an aggregation inside another aggregation, such as
count(count by (pod) (up)) / sum(machine_count). Nested aggregations on their own, such assum(sum by (pod) (...)), are supported.(9.5+; Serverless) Binary expressions where both operands read metrics and the operands aren't aggregated alike. Both operands must be either not aggregated, such as
a / b, or aggregated once across series, such assum(a) / sum(b). Mixing an aggregated and a non-aggregated operand (sum(a) / b), combiningscalar()of a metric with an operand that has labels (b / scalar(sum(a))), and usingtopk,bottomk,limitk, orlimit_ratioin an operand return a client error (4xx). Operations with a number, such astopk(1, a) * 2, are supported. This restriction doesn't apply toor.(9.5+; Serverless)
histogram_quantileandhistogram_fractionovertopk,bottomk,limitk,limit_ratio, or awithout(...)aggregation, unless the input is first aggregated withby(...). For example,histogram_quantile(0.9, topk(5, a))returns a client error (4xx), buthistogram_quantile(0.9, topk(5, sum by (job, le) (a)))is supported.Functions: refer to Not yet supported for the full list of recognized but unimplemented functions. Some supported functions have restrictions, which are listed under Differences from Prometheus on each function's reference entry.
(9.4 only, preview) Binary set operator
or.(9.4 only, preview) The
offsetmodifier.
The following constructs return no results instead of an error:
Binary expressions between two operands that read different metrics without aggregating them, such as
node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes. Unlike in Prometheus, the series of the two metrics aren't matched on their other labels. Aggregate both operands by the labels to keep instead, such asavg by (instance) (node_memory_MemAvailable_bytes) / avg by (instance) (node_memory_MemTotal_bytes).
For behavioral differences from Prometheus, refer to PromQL limitations.
Examples
Fully adaptive query
Rely on Kibana's date picker for the time range, and let step and range selectors be inferred automatically:
PROMQL index=metrics-generic.prometheus-* http_rate=(sum(rate(http_requests_total)))This is the recommended pattern for Kibana dashboards. The query responds to the date picker, adjusts the step size to the selected time range, and sizes the range selector window accordingly.
Instant query
(9.5+; Serverless) Evaluate the expression once, for example to get the current value of a metric:
PROMQL index=metrics-generic.prometheus-*
time="2026-04-01T01:00:00Z"
http_rate=(sum(rate(http_requests_total)))Cross-series aggregation by label
PROMQL index=k8s step=1h result=(sum by (cluster) (network.cost))
| SORT result| result:double | step:datetime | cluster:keyword |
|---|---|---|
| 15.875 | 2024-05-10T00:00:00.000Z | staging |
| 18.625 | 2024-05-10T00:00:00.000Z | prod |
| 26.5 | 2024-05-10T00:00:00.000Z | qa |
Label filtering with named result
PROMQL index=k8s step=1h cost=(max by (cluster) (network.total_bytes_in{cluster!="prod"}))
| SORT cluster| cost:double | step:datetime | cluster:keyword |
|---|---|---|
| 10797.0 | 2024-05-10T00:00:00.000Z | qa |
| 7403.0 | 2024-05-10T00:00:00.000Z | staging |
Post-processing with ES|QL
Pipe PromQL results into ES|QL commands for further aggregation:
PROMQL index=k8s step=1h bytes=(max by (cluster) (network.bytes_in))
| STATS max_bytes=MAX(bytes) BY cluster
| SORT cluster| max_bytes:double | cluster:keyword |
|---|---|
| 931.0 | prod |
| 972.0 | qa |
| 238.0 | staging |
Ad-hoc query with inferred step
For queries outside Kibana, set start and end explicitly. The step and range selector are still inferred
automatically from the time range and the default buckets count:
PROMQL index=metrics-generic.prometheus-*
start="2026-04-01T00:00:00Z"
end="2026-04-01T01:00:00Z"
http_rate=(sum(rate(http_requests_total)))Enrich with a lookup
Join PromQL results with external data using ES|QL commands:
PROMQL index=metrics-generic.prometheus-*
http_rate=(sum by (instance) (rate(http_requests_total)))
| LOOKUP JOIN instance_metadata ON instance<!-- end-docs: esql/commands/promql -->
When to Use PROMQL
Prefer PROMQL when any of the following apply:
The user explicitly asks for a PromQL query, references Prometheus syntax (
sum by (instance) (...), label matchers like{cluster="prod"}, etc), or is migrating a Prometheus dashboard or alert.Compatibility with Prometheus tooling is required (Grafana panels, alerting rules, scripts that already speak PromQL).
The user wrote ES|QL (or is asking in natural language without PromQL terms) and the query is naturally expressed in the inner/outer aggregation paradigm (
SUM(RATE(...)),AVG(AVG_OVER_TIME(...))).The query mixes time series with non-time-series data sources or uses ES|QL features like
LOOKUP JOIN,CHANGE_POINT, orINLINE STATSbefore the metrics aggregation.
| Aspect | PROMQL | TS |
|---|---|---|
| Syntax | Prometheus Query Language | ES|QL inner/outer aggregation |
| Default index | metrics-* | None — caller must specify |
| Time filtering | start/end options or Kibana date picker | WHERE TRANGE(...) or WHERE @timestamp ... |
| Bucketing | step / buckets, or time (instant, 9.5+) | BY TBUCKET(interval) |
| Range vector window | Implicit (max(step, scrape_interval)) | Bucket interval, or sliding window arg (9.3+) |
| Counter aggregation | sum(rate(metric)) | STATS SUM(RATE(metric)) BY TBUCKET(...) |
| Gauge aggregation | avg_over_time(metric[5m]) | STATS AVG(AVG_OVER_TIME(metric)) BY TBUCKET(...) |
| Label filtering | metric{cluster="prod"} | WHERE cluster == "prod" |
| Availability | 9.4 (preview), GA in 9.5 | 9.2 (preview), GA in 9.4 |
Both commands target TSDS indices and can be followed by the same set of ES|QL processing commands.
Running PROMQL Queries
<!-- Candidates for the Elasticsearch docs: once a fact is documented there, remove it here. -->
Rows are not returned in time order. That's fine for Kibana charts, which order by
stepthemselves._timeseriesis opaque to later commands. Functions that keep series identity, such astopk, also return_timeseries. Dotted labels are nested in its JSON ({"host":{"name":"web-01"}}). To use a label inSTATS,WHERE, orLOOKUP JOIN, group by it withby (...).Unknown metric or label names are not errors. As in Prometheus, a selector that matches nothing returns an empty result. If a query returns no rows, verify the metric names first (for example with
TS <index> | METRICS_INFO, see time-series-queries.md) rather than assuming no data.
Handling Unsupported Constructs
Check Limitations before writing the query, and write everything else in standard PromQL.
Run it. Unsupported constructs are rejected with a
400verification_exceptionthat names the construct, for exampleFunction [predict_linear] is not yet implementedorset operator [and] is not supported at this time. This is the reliable check for functions and for clusters on older versions.On such an error, check the PromQL functions and PromQL operators references for the construct and its availability on the cluster version.
Tell the user which construct is not supported on their deployment, rather than silently rewriting the query into something with different semantics, and offer an equivalent
TSquery if there is one. To add labels from a lookup index instead of using group modifiers, useLOOKUP JOINafterPROMQL.
Stack 9.4 and 9.5 fallbacks
topk,bottomk,limitk,predict_linear,absent, andlabel_replaceare unavailable on Stack 9.4 and 9.5. For top or bottom N series, drop the function and rank each step in ES|QL (ASCforbottomk); for the others, tell the user:PROMQL index=metrics-tsds step=5m start="2026-10-22T13:00:00Z" end="2026-10-22T15:00:00Z" r=(sum by (host) (rate(requests))) | SORT step, r DESC | LIMIT 2 BY step9.4 has no working instant query (
time=fails withunable to create a bucket). For one value per series, run a range query withstepequal toend - start, andstarta multiple ofstep: steps snap to epoch-aligned boundaries, so an unaligned window returns two rows per series.PROMQL index=metrics-tsds step=2h start="2026-10-22T12:00:00Z" end="2026-10-22T14:00:00Z" r=(sum by (host) (rate(requests)))
Kibana Charts
For time series charts, use the PROMQL command as is: it already returns one row per series and step, and the chart
uses step as its time axis. Since the output has no @timestamp column, do not add a WHERE time filter, BUCKET,
or TBUCKET after PROMQL. For metric and gauge charts or rankings, use an instant query (refer to
single-value results).
Guidelines
Prefer
PROMQLonly when the user thinks in PromQL or is porting a Prometheus query or dashboard. Otherwise, preferTS, which integrates more naturally with the rest of ES|QL.For a relative time range outside Kibana, such as the last hour, compute absolute timestamps. Pass Unix timestamps in seconds, not milliseconds.
Group only by the labels you break down by. For one value overall, aggregate across all series without grouping, such as
sum(rate(http_requests_total)), rather than grouping by a label first and then aggregating the groups again.Write one expression per
PROMQLcommand. Combine values into one expression if they form a single value, such assum(rate(rx_bytes)) + sum(rate(tx_bytes)). Otherwise, write one query per expression, and never silently drop one.
References
ES|QL PROMQL command: official documentation, mirrored above
PromQL in Elasticsearch: overview, differences from Prometheus
PromQL functions: supported functions and per-version availability
PromQL operators: supported operators and vector-matching modifiers
Prometheus Query Language: PromQL fundamentals
time-series-queries.md:
TScommand and ES|QL native time series functionsesql-version-history.md: feature availability by Elasticsearch version
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
The author says: Elasticsearch 8.14 or later (ES|QL GA; introduced 8.11 as tech preview), self-managed, Elastic Cloud Hosted, or Elastic Cloud Serverless; individual ES|QL features are version-gated (see references/esql-version-history.md). Requires the `elastic` CLI ≥ 0.2 with `stack es` support.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- elastic
- Publisher
- Elastic (Official)
- Source
- elastic/agent-skills · skills/elasticsearch/elasticsearch-esql · commit 09d879d
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Also distributed in
- elastic/agent-skills
AutoGineer is not affiliated with or endorsed by elastic.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download elasticsearch-esql.zip