From 8b20dd8ec2575160e3febce9c7f69eab51d34fc7 Mon Sep 17 00:00:00 2001 From: Liam Thompson Date: Tue, 23 Jul 2024 12:32:52 +0200 Subject: [PATCH] [DOCS][ESQL] Document how named parameters work --- docs/reference/esql/esql-rest.asciidoc | 34 +++++++++++++++++--------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/docs/reference/esql/esql-rest.asciidoc b/docs/reference/esql/esql-rest.asciidoc index 5b90e96d7a734..94f8cf828884d 100644 --- a/docs/reference/esql/esql-rest.asciidoc +++ b/docs/reference/esql/esql-rest.asciidoc @@ -238,8 +238,13 @@ POST /_query [[esql-rest-params]] ==== Passing parameters to a query -Values, for example for a condition, can be passed to a query "inline", by -integrating the value in the query string itself: +Values can be passed to a query either inline, by integrating the value directly in the query string, or by using parameters to prevent code injection and simplify query management. There are two main approaches to parameterizing queries: positional parameters and named parameters. + +[discrete] +[[esql-rest-params-positional]] +===== Positional parameters + +With positional parameters, values are passed using question mark placeholders (`?`), which are replaced in the order that parameters appear in the `params` array. [source,console] ---- @@ -248,18 +253,21 @@ POST /_query "query": """ FROM library | EVAL year = DATE_EXTRACT("year", release_date) - | WHERE page_count > 300 AND author == "Frank Herbert" + | WHERE page_count > ? AND author == ? | STATS count = COUNT(*) by year - | WHERE count > 0 + | WHERE count > ? | LIMIT 5 - """ + """, + "params": [300, "Frank Herbert", 10] } ---- // TEST[setup:library] -To avoid any attempts of hacking or code injection, extract the values in a -separate list of parameters. Use question mark placeholders (`?`) in the query -string for each of the parameters: +[discrete] +[[esql-rest-params-named]] +===== Named parameters + +Named parameters enable you to specify parameters with names, instead of by their position in the array. This makes queries more readable and helps reduces errors. [source,console] ---- @@ -268,12 +276,16 @@ POST /_query "query": """ FROM library | EVAL year = DATE_EXTRACT("year", release_date) - | WHERE page_count > ? AND author == ? + | WHERE page_count > ?minPageCount AND author == ?authorName | STATS count = COUNT(*) by year - | WHERE count > ? + | WHERE count > ?minCount | LIMIT 5 """, - "params": [300, "Frank Herbert", 0] + "params": [ + {"name": "minPageCount", "value": 300}, + {"name": "authorName", "value": "Frank Herbert"}, + {"name": "minCount", "value": 0} + ] } ---- // TEST[setup:library]