template-query.asciidoc 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. [[java-query-dsl-template-query]]
  2. ==== Template Query
  3. See {ref}/search-template.html[Search Template] documentation
  4. Define your template parameters as a `Map<String,Object>`:
  5. [source,java]
  6. --------------------------------------------------
  7. Map<String, Object> template_params = new HashMap<>();
  8. template_params.put("param_gender", "male");
  9. --------------------------------------------------
  10. You can use your stored search templates in `config/scripts`.
  11. For example, if you have a file named `config/scripts/template_gender.mustache` containing:
  12. [source,js]
  13. --------------------------------------------------
  14. {
  15. "template" : {
  16. "query" : {
  17. "match" : {
  18. "gender" : "{{param_gender}}"
  19. }
  20. }
  21. }
  22. }
  23. --------------------------------------------------
  24. Define your template query:
  25. [source,java]
  26. --------------------------------------------------
  27. QueryBuilder qb = templateQuery(
  28. "gender_template", <1>
  29. ScriptService.ScriptType.FILE, <2>
  30. template_params); <3>
  31. --------------------------------------------------
  32. <1> template name
  33. <2> template stored on disk in `gender_template.mustache`
  34. <3> parameters
  35. You can also store your template in a special index named `.scripts`:
  36. [source,java]
  37. --------------------------------------------------
  38. client.preparePutIndexedScript("mustache", "template_gender",
  39. "{\n" +
  40. " \"template\" : {\n" +
  41. " \"query\" : {\n" +
  42. " \"match\" : {\n" +
  43. " \"gender\" : \"{{param_gender}}\"\n" +
  44. " }\n" +
  45. " }\n" +
  46. " }\n" +
  47. "}").get();
  48. --------------------------------------------------
  49. To execute an indexed templates, use `ScriptService.ScriptType.INDEXED`:
  50. [source,java]
  51. --------------------------------------------------
  52. QueryBuilder qb = templateQuery(
  53. "gender_template", <1>
  54. ScriptService.ScriptType.INDEXED, <2>
  55. template_params); <3>
  56. --------------------------------------------------
  57. <1> template name
  58. <2> template stored in an index
  59. <3> parameters