search_queries_script.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2012-present 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. import "errors"
  6. // ScriptQuery allows to define scripts as filters.
  7. //
  8. // For details, see
  9. // https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-script-query.html
  10. type ScriptQuery struct {
  11. script *Script
  12. queryName string
  13. }
  14. // NewScriptQuery creates and initializes a new ScriptQuery.
  15. func NewScriptQuery(script *Script) *ScriptQuery {
  16. return &ScriptQuery{
  17. script: script,
  18. }
  19. }
  20. // QueryName sets the query name for the filter that can be used
  21. // when searching for matched_filters per hit
  22. func (q *ScriptQuery) QueryName(queryName string) *ScriptQuery {
  23. q.queryName = queryName
  24. return q
  25. }
  26. // Source returns JSON for the query.
  27. func (q *ScriptQuery) Source() (interface{}, error) {
  28. if q.script == nil {
  29. return nil, errors.New("ScriptQuery expected a script")
  30. }
  31. source := make(map[string]interface{})
  32. params := make(map[string]interface{})
  33. source["script"] = params
  34. src, err := q.script.Source()
  35. if err != nil {
  36. return nil, err
  37. }
  38. params["script"] = src
  39. if q.queryName != "" {
  40. params["_name"] = q.queryName
  41. }
  42. return source, nil
  43. }