search_queries_template_query.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2012-2015 Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. // TemplateQuery is a query that accepts a query template and a
  6. // map of key/value pairs to fill in template parameters.
  7. //
  8. // For more details, see:
  9. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-template-query.html
  10. type TemplateQuery struct {
  11. vars map[string]interface{}
  12. template string
  13. templateType string
  14. }
  15. // NewTemplateQuery creates a new TemplateQuery.
  16. func NewTemplateQuery(name string) TemplateQuery {
  17. return TemplateQuery{
  18. template: name,
  19. vars: make(map[string]interface{}),
  20. }
  21. }
  22. // Template specifies the name of the template.
  23. func (q TemplateQuery) Template(name string) TemplateQuery {
  24. q.template = name
  25. return q
  26. }
  27. // TemplateType defines which kind of query we use. The values can be:
  28. // inline, indexed, or file. If undefined, inline is used.
  29. func (q TemplateQuery) TemplateType(typ string) TemplateQuery {
  30. q.templateType = typ
  31. return q
  32. }
  33. // Var sets a single parameter pair.
  34. func (q TemplateQuery) Var(name string, value interface{}) TemplateQuery {
  35. q.vars[name] = value
  36. return q
  37. }
  38. // Vars sets parameters for the template query.
  39. func (q TemplateQuery) Vars(vars map[string]interface{}) TemplateQuery {
  40. q.vars = vars
  41. return q
  42. }
  43. // Source returns the JSON serializable content for the search.
  44. func (q TemplateQuery) Source() interface{} {
  45. // {
  46. // "template" : {
  47. // "query" : {"match_{{template}}": {}},
  48. // "params" : {
  49. // "template": "all"
  50. // }
  51. // }
  52. // }
  53. query := make(map[string]interface{})
  54. tmpl := make(map[string]interface{})
  55. query["template"] = tmpl
  56. // TODO(oe): Implementation differs from online documentation at http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-template-query.html
  57. var fieldname string
  58. switch q.templateType {
  59. case "file": // file
  60. fieldname = "file"
  61. case "indexed", "id": // indexed
  62. fieldname = "id"
  63. default: // inline
  64. fieldname = "query"
  65. }
  66. tmpl[fieldname] = q.template
  67. if len(q.vars) > 0 {
  68. tmpl["params"] = q.vars
  69. }
  70. return query
  71. }