search_queries_terms.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. // A query that match on any (configurable) of the provided terms.
  6. // This is a simpler syntax query for using a bool query with
  7. // several term queries in the should clauses.
  8. // For more details, see
  9. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html
  10. type TermsQuery struct {
  11. Query
  12. name string
  13. values []interface{}
  14. minimumShouldMatch string
  15. disableCoord *bool
  16. boost *float32
  17. queryName string
  18. }
  19. // NewTermsQuery creates a new terms query.
  20. func NewTermsQuery(name string, values ...interface{}) TermsQuery {
  21. t := TermsQuery{
  22. name: name,
  23. values: make([]interface{}, 0),
  24. }
  25. if len(values) > 0 {
  26. t.values = append(t.values, values...)
  27. }
  28. return t
  29. }
  30. func (q TermsQuery) MinimumShouldMatch(minimumShouldMatch string) TermsQuery {
  31. q.minimumShouldMatch = minimumShouldMatch
  32. return q
  33. }
  34. func (q TermsQuery) DisableCoord(disableCoord bool) TermsQuery {
  35. q.disableCoord = &disableCoord
  36. return q
  37. }
  38. func (q TermsQuery) Boost(boost float32) TermsQuery {
  39. q.boost = &boost
  40. return q
  41. }
  42. func (q TermsQuery) QueryName(queryName string) TermsQuery {
  43. q.queryName = queryName
  44. return q
  45. }
  46. // Creates the query source for the term query.
  47. func (q TermsQuery) Source() interface{} {
  48. // {"terms":{"name":["value1","value2"]}}
  49. source := make(map[string]interface{})
  50. params := make(map[string]interface{})
  51. source["terms"] = params
  52. params[q.name] = q.values
  53. if q.minimumShouldMatch != "" {
  54. params["minimum_should_match"] = q.minimumShouldMatch
  55. }
  56. if q.disableCoord != nil {
  57. params["disable_coord"] = *q.disableCoord
  58. }
  59. if q.boost != nil {
  60. params["boost"] = *q.boost
  61. }
  62. if q.queryName != "" {
  63. params["_name"] = q.queryName
  64. }
  65. return source
  66. }