search_queries_term.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. // TermQuery finds documents that contain the exact term specified
  6. // in the inverted index.
  7. //
  8. // For details, see
  9. // https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-term-query.html
  10. type TermQuery struct {
  11. name string
  12. value interface{}
  13. boost *float64
  14. queryName string
  15. }
  16. // NewTermQuery creates and initializes a new TermQuery.
  17. func NewTermQuery(name string, value interface{}) *TermQuery {
  18. return &TermQuery{name: name, value: value}
  19. }
  20. // Boost sets the boost for this query.
  21. func (q *TermQuery) Boost(boost float64) *TermQuery {
  22. q.boost = &boost
  23. return q
  24. }
  25. // QueryName sets the query name for the filter that can be used
  26. // when searching for matched_filters per hit
  27. func (q *TermQuery) QueryName(queryName string) *TermQuery {
  28. q.queryName = queryName
  29. return q
  30. }
  31. // Source returns JSON for the query.
  32. func (q *TermQuery) Source() (interface{}, error) {
  33. // {"term":{"name":"value"}}
  34. source := make(map[string]interface{})
  35. tq := make(map[string]interface{})
  36. source["term"] = tq
  37. if q.boost == nil && q.queryName == "" {
  38. tq[q.name] = q.value
  39. } else {
  40. subQ := make(map[string]interface{})
  41. subQ["value"] = q.value
  42. if q.boost != nil {
  43. subQ["boost"] = *q.boost
  44. }
  45. if q.queryName != "" {
  46. subQ["_name"] = q.queryName
  47. }
  48. tq[q.name] = subQ
  49. }
  50. return source, nil
  51. }