@elastic/esql

中文文档
4.39.0发布于 2026/11/11Elastic-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 69.6万

A set of ts tools to parse, build and transform ES|QL queries programmatically.

原始使用文档
文档目录13 节
  1. Installation
  2. Sub-module reference
  3. Creating an ES|QL AST
  4. Parsing a query
  5. Composing a query
  6. Building AST nodes manually
  7. Traversing an ES|QL AST
  8. Walker
  9. Visitor
  10. Modifying an ES|QL AST
  11. Pretty-printing
  12. PromQL support
  13. Licence

@elastic/esql

Grammar Sync NPM version

ES|QL and PromQL parser, AST builder, traversal, mutation, and pretty-printing for JavaScript and TypeScript. Used in Kibana and other Elastic tooling.

Installation

npm yarn pnpm
npm install @elastic/esql
yarn add @elastic/esql
pnpm add @elastic/esql

Sub-module reference

ModuleDescription
src/parser/Parser class — parse query strings to AST
src/composer/esql tagged-template query builder
src/composer/synth/synth — synthesize AST nodes from template strings; PromQL node builders
src/ast/builder/Builder — low-level AST node construction
src/ast/walker/Walker — simple full-tree traversal
src/ast/visitor/Visitor — typed, controlled traversal with input/output passing
src/ast/mutate/mutate — named helpers for structural AST edits
src/pretty_print/BasicPrettyPrinter, WrappingPrettyPrinter

Creating an ES|QL AST

Parsing a query

The Parser converts a query string into an AST synchronously.

import { Parser } from '@elastic/esql';

const { root, errors } = Parser.parse('FROM index | WHERE col0 > 100');

Pass { withFormatting: true } to attach comments and whitespace to AST nodes (needed for round-trip formatting):

const { root } = Parser.parse('FROM /* comment */ index', { withFormatting: true });

Parse a single command or expression without a full query string:

const { root: expr } = Parser.parseExpression('count(*) + 1');
const { root: cmd } = Parser.parseCommand('WHERE col > 10');

Composing a query

The esql composer is a tagged-template API for building queries with safe parameter injection:

import { esql } from '@elastic/esql';

const start = '2024-01-01';
const limit = 100;

const query = esql`
  FROM index
    | WHERE @timestamp >= ${{ start }}
    | SORT @timestamp DESC
    | KEEP service.name, log.level`;

query.pipe`LIMIT ${{ limit }}`;

// Get the Elasticsearch request payload:
query.toRequest();
// { query: 'FROM index | WHERE @timestamp >= ?start | ...', params: [{ start: '2024-01-01' }, ...] }

Use .query to append multiple piped commands at once:

query.query`WHERE status == ${{ status }} | STATS count = COUNT(*) | LIMIT ${{ limit }}`;

See the synth API for synthesizing individual AST nodes from template strings.

Building AST nodes manually

The Builder is a low-level API for constructing AST nodes programmatically:

import { Builder } from '@elastic/esql';

const node = Builder.command({
  name: 'limit',
  args: [Builder.expression.literal.integer(10)],
});

Traversing an ES|QL AST

Walker

The Walker visits every node in the AST, calling your callbacks for each node type:

import { Walker } from '@elastic/esql';
import type { ESQLCommand, ESQLFunction } from '@elastic/esql-types';

const walker = new Walker({
  visitCommand: (node: ESQLCommand) => {
    console.log('command:', node.name);
  },
  visitFunction: (fn: ESQLFunction) => {
    console.log('function:', fn.name);
  },
});

walker.walk(root);

Static helpers like Walker.findAll(), Walker.params(), and Walker.replace() cover the most common search-and-modify patterns without needing to instantiate a walker.

The walker also traverses embedded PromQL expressions — see PromQL support in the walker docs.

Visitor

The Visitor provides a more powerful traversal model where you control which children to visit, and callbacks can pass typed values up and down the tree:

import { Visitor } from '@elastic/esql';

const columnNames = new Visitor()
  .on('visitColumnExpression', (ctx) => ctx.node.name)
  .on('visitExpression', () => null)
  .on('visitCommand', (ctx) => [...ctx.visitArguments()])
  .on('visitQuery', (ctx) => [...ctx.visitCommands()])
  .visitQuery(root);

Modifying an ES|QL AST

The mutate API provides named methods for common structural edits:

import { Parser, mutate, BasicPrettyPrinter } from '@elastic/esql';

const { root } = Parser.parse('FROM index METADATA _lang');

console.log([...mutate.commands.from.metadata.list(root)]);
// [ '_lang' ]

mutate.commands.from.metadata.upsert(root, '_id');

console.log([...mutate.commands.from.metadata.list(root)]);
// [ '_lang', '_id' ]

console.log(BasicPrettyPrinter.print(root));
// FROM index METADATA _lang, _id

Pretty-printing

The pretty_print module formats an AST back to a query string.

BasicPrettyPrinter — single-line or pipe-separated multiline output:

import { Parser, BasicPrettyPrinter } from '@elastic/esql';

const { root } = Parser.parse('FROM index | WHERE x > 100 | LIMIT 100');

BasicPrettyPrinter.print(root);
// FROM index | WHERE x > 100 | LIMIT 100

BasicPrettyPrinter.multiline(root, { pipeTab: '  ' });
// FROM index
//   | WHERE x > 100
//   | LIMIT 100

WrappingPrettyPrinter — width-aware, preserves comments (requires { withFormatting: true } on parse):

import { Parser, WrappingPrettyPrinter } from '@elastic/esql';

const { root } = Parser.parse(
  'FROM index /* source */ | WHERE x > 100 | LIMIT 100',
  { withFormatting: true },
);

console.log(WrappingPrettyPrinter.print(root, { multiline: true }));
// FROM index /* source */
// | WHERE x > 100
// | LIMIT 100

PromQL support

ES|QL embeds PromQL via the PROMQL source command. Use esql.promql() in the composer:

import { esql } from '@elastic/esql';

esql.promql(esql.pql`sum(rate(metric[5m])) by (job)`)
  .where`value > 0`
  .limit(100)
  .print();
// PROMQL (sum(rate(metric[5m])) by (job)) | WHERE value > 0 | LIMIT 100

See the synth README for pql, pqlSel, pqlFunc, and other PromQL node builders.

Licence

Licensed under Elastic License 2.0.

版本与发布记录

@elastic/esql 共发布 68 个版本,首次发布于 2026/02/24;过去 12 个月发布了 68 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.39.0latest2026/11/112 天前
4.38.02026/11/094 天前
4.37.02026/11/058 天前
4.36.02026/11/0211 天前
4.35.02026/10/2915 天前
4.34.02026/10/2618 天前

其他发布通道:beta → 0.0.4。

关于 @elastic/esql 的常见问题

@elastic/esql 是什么?

A set of ts tools to parse, build and transform ES|QL queries programmatically.

如何安装 @elastic/esql?

在项目目录运行 npm install @elastic/esql,或使用 pnpm add / yarn add / bun add。

@elastic/esql 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@elastic/esql 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@elastic/esql 可以商用吗?

@elastic/esql 使用 Elastic-2.0 许可。声明的许可为 Elastic-2.0,请阅读许可原文确认使用条件。以上为概括,不构成法律意见,请以许可原文为准。

@elastic/esql 的下载量有多少?

根据 npm 官方下载统计,@elastic/esql 在 2026/10/14 – 2026/11/12 这 30 天内被下载 695,576 次,日均约 23,186 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@elastic/esql 还在维护吗?

最新版本 4.39.0 发布于 2026/11/11(2 天前);至今共发布 68 个版本,其中过去 12 个月发布了 68 个;首次发布于 2026/02/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。