search_queries_terms.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // TermsQuery filters documents that have fields that match any
  6. // of the provided terms (not analyzed).
  7. //
  8. // For more details, see
  9. // https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-terms-query.html
  10. type TermsQuery struct {
  11. name string
  12. values []interface{}
  13. termsLookup *TermsLookup
  14. queryName string
  15. boost *float64
  16. }
  17. // NewTermsQuery creates and initializes a new TermsQuery.
  18. func NewTermsQuery(name string, values ...interface{}) *TermsQuery {
  19. q := &TermsQuery{
  20. name: name,
  21. values: make([]interface{}, 0),
  22. }
  23. if len(values) > 0 {
  24. q.values = append(q.values, values...)
  25. }
  26. return q
  27. }
  28. // TermsLookup adds terms lookup details to the query.
  29. func (q *TermsQuery) TermsLookup(lookup *TermsLookup) *TermsQuery {
  30. q.termsLookup = lookup
  31. return q
  32. }
  33. // Boost sets the boost for this query.
  34. func (q *TermsQuery) Boost(boost float64) *TermsQuery {
  35. q.boost = &boost
  36. return q
  37. }
  38. // QueryName sets the query name for the filter that can be used
  39. // when searching for matched_filters per hit
  40. func (q *TermsQuery) QueryName(queryName string) *TermsQuery {
  41. q.queryName = queryName
  42. return q
  43. }
  44. // Creates the query source for the term query.
  45. func (q *TermsQuery) Source() (interface{}, error) {
  46. // {"terms":{"name":["value1","value2"]}}
  47. source := make(map[string]interface{})
  48. params := make(map[string]interface{})
  49. source["terms"] = params
  50. if q.termsLookup != nil {
  51. src, err := q.termsLookup.Source()
  52. if err != nil {
  53. return nil, err
  54. }
  55. params[q.name] = src
  56. } else {
  57. params[q.name] = q.values
  58. if q.boost != nil {
  59. params["boost"] = *q.boost
  60. }
  61. if q.queryName != "" {
  62. params["_name"] = q.queryName
  63. }
  64. }
  65. return source, nil
  66. }