search_queries_prefix.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. // Matches documents that have fields containing terms
  6. // with a specified prefix (not analyzed).
  7. // For more details, see
  8. // http://www.elasticsearch.org/guide/reference/query-dsl/prefix-query.html
  9. type PrefixQuery struct {
  10. Query
  11. name string
  12. prefix string
  13. boost *float32
  14. rewrite string
  15. queryName string
  16. }
  17. // Creates a new prefix query.
  18. func NewPrefixQuery(name string, prefix string) PrefixQuery {
  19. q := PrefixQuery{name: name, prefix: prefix}
  20. return q
  21. }
  22. func (q PrefixQuery) Boost(boost float32) PrefixQuery {
  23. q.boost = &boost
  24. return q
  25. }
  26. func (q PrefixQuery) Rewrite(rewrite string) PrefixQuery {
  27. q.rewrite = rewrite
  28. return q
  29. }
  30. func (q PrefixQuery) QueryName(queryName string) PrefixQuery {
  31. q.queryName = queryName
  32. return q
  33. }
  34. // Creates the query source for the prefix query.
  35. func (q PrefixQuery) Source() interface{} {
  36. // {
  37. // "prefix" : {
  38. // "user" : {
  39. // "prefix" : "ki",
  40. // "boost" : 2.0
  41. // }
  42. // }
  43. // }
  44. source := make(map[string]interface{})
  45. query := make(map[string]interface{})
  46. source["prefix"] = query
  47. if q.boost == nil && q.rewrite == "" && q.queryName == "" {
  48. query[q.name] = q.prefix
  49. } else {
  50. subQuery := make(map[string]interface{})
  51. subQuery["prefix"] = q.prefix
  52. if q.boost != nil {
  53. subQuery["boost"] = *q.boost
  54. }
  55. if q.rewrite != "" {
  56. subQuery["rewrite"] = q.rewrite
  57. }
  58. if q.queryName != "" {
  59. subQuery["_name"] = q.queryName
  60. }
  61. query[q.name] = subQuery
  62. }
  63. return source
  64. }