The ES|QL mutation API provides methods to navigate and modify the AST.
For example, insert a FROM command METADATA field:
import { parse, mutate, BasicPrettyPrinter } from '@elastic/esql';
const { root } = 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' ]
const src = BasicPrettyPrinter.print(root);
console.log(src); // FROM index METADATA _lang, _id.generic.listCommands()— Lists all commands. Returns an iterator..findCommand()— Finds a specific command by a predicate function..findCommandOption()— Finds a specific command option by a predicate function..findCommandByName()— Finds a specific command by name..findCommandOptionByName()— Finds a specific command option by name..appendCommand()— Add a new command to the AST..appendCommandOption()— Add a new command option to a command..appendCommandArgument()— Add a new main command argument to a command..removeCommand()— Remove a command from the AST..removeCommandOption()— Remove a command option from the AST..removeCommandArgument()— Remove a command argument from the AST.
.commands.from.sources.list()— List allFROMsources..find()— Find a source by name..remove()— Remove a source by name..insert()— Insert a source..upsert()— Insert a source, if it does not exist.
.metadata.list()— List allMETADATAfields..find()— Find aMETADATAfield by name..removeByPredicate()— Remove aMETADATAfield by matching a predicate function..remove()— Remove aMETADATAfield by name..insert()— Insert aMETADATAfield..upsert()— InsertMETADATAfield, if it does not exist.
.limit.list()— List allLIMITcommands..byIndex()— Find aLIMITcommand by index..find()— Find aLIMITcommand by a predicate function..remove()— Remove aLIMITcommand by index..set()— Set the limit value of a specificLIMITcommand..upsert()— Insert aLIMITcommand, or update the limit value if it already exists.
.stats.list()— List allSTATScommands..byIndex()— Find aSTATScommand by index.
.join.list()— List allJOINcommands..byIndex()— Find aJOINcommand by index.
.set.list()— List allSETheader commands..findBySettingName()— Find aSETcommand by its setting name..update()— Modify the value of an existingSETsetting..upsert()— Modify aSETsetting value, or add a newSETcommand if it does not exist..remove()— Deletes a SET command by setting name.