template-query.asciidoc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. [[query-dsl-template-query]]
  2. === Template Query
  3. coming[1.1.0]
  4. A query that accepts a query template and a map of key/value pairs to fill in
  5. template parameters.
  6. [source,js]
  7. ------------------------------------------
  8. GET /_search
  9. {
  10. "query": {
  11. "template": {
  12. "query": {"match_{{template}}": {}},
  13. "params" : {
  14. "template" : "all"
  15. }
  16. }
  17. }
  18. }
  19. ------------------------------------------
  20. Alternatively passing the template as an escaped string works as well:
  21. [source,js]
  22. ------------------------------------------
  23. GET /_search
  24. {
  25. "query": {
  26. "template": {
  27. "query": "{\"match_{{template}}\": {}}\"", <1>
  28. "params" : {
  29. "template" : "all"
  30. }
  31. }
  32. }
  33. }
  34. ------------------------------------------
  35. <1> New line characters (`\n`) should be escaped as `\\n` or removed,
  36. and quotes (`"`) should be escaped as `\\"`.
  37. You can register a template by storing it in the `config/scripts` directory.
  38. In order to execute the stored template, reference it by name in the `query`
  39. parameter:
  40. [source,js]
  41. ------------------------------------------
  42. GET /_search
  43. {
  44. "query": {
  45. "template": {
  46. "query": "storedTemplate", <1>
  47. "params" : {
  48. "template" : "all"
  49. }
  50. }
  51. }
  52. }
  53. ------------------------------------------
  54. <1> Name of the the query template in `config/scripts/`.
  55. Templating is based on Mustache. For simple token substitution all you provide
  56. is a query containing some variable that you want to substitute and the actual
  57. values:
  58. [source,js]
  59. ------------------------------------------
  60. GET /_search
  61. {
  62. "query": {
  63. "template": {
  64. "query": {"match_{{template}}": {}},
  65. "params" : {
  66. "template" : "all"
  67. }
  68. }
  69. }
  70. }
  71. ------------------------------------------
  72. which is then turned into:
  73. [source,js]
  74. ------------------------------------------
  75. {
  76. "query": {
  77. "match_all": {}
  78. }
  79. }
  80. ------------------------------------------
  81. There is also a dedicated `template` endpoint, which allows you to specify the template query directly.
  82. You can use the `/_search/template` endpoint for that. Please see <<search-template>> for more details.