search_queries_prefix.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // PrefixQuery matches documents that have fields containing terms
  6. // with a specified prefix (not analyzed).
  7. //
  8. // For more details, see
  9. // https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-prefix-query.html
  10. type PrefixQuery struct {
  11. name string
  12. prefix string
  13. boost *float64
  14. rewrite string
  15. queryName string
  16. }
  17. // NewPrefixQuery creates and initializes a new PrefixQuery.
  18. func NewPrefixQuery(name string, prefix string) *PrefixQuery {
  19. return &PrefixQuery{name: name, prefix: prefix}
  20. }
  21. // Boost sets the boost for this query.
  22. func (q *PrefixQuery) Boost(boost float64) *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. // QueryName sets the query name for the filter that can be used when
  31. // searching for matched_filters per hit.
  32. func (q *PrefixQuery) QueryName(queryName string) *PrefixQuery {
  33. q.queryName = queryName
  34. return q
  35. }
  36. // Source returns JSON for the query.
  37. func (q *PrefixQuery) Source() (interface{}, error) {
  38. source := make(map[string]interface{})
  39. query := make(map[string]interface{})
  40. source["prefix"] = query
  41. if q.boost == nil && q.rewrite == "" && q.queryName == "" {
  42. query[q.name] = q.prefix
  43. } else {
  44. subQuery := make(map[string]interface{})
  45. subQuery["value"] = q.prefix
  46. if q.boost != nil {
  47. subQuery["boost"] = *q.boost
  48. }
  49. if q.rewrite != "" {
  50. subQuery["rewrite"] = q.rewrite
  51. }
  52. if q.queryName != "" {
  53. subQuery["_name"] = q.queryName
  54. }
  55. query[q.name] = subQuery
  56. }
  57. return source, nil
  58. }