search_queries_nested.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. // Nested query allows to query nested objects / docs (see nested mapping).
  6. // The query is executed against the nested objects / docs as if they were
  7. // indexed as separate docs (they are, internally) and resulting in the
  8. // root parent doc (or parent nested mapping).
  9. //
  10. // For more details, see:
  11. // http://www.elasticsearch.org/guide/reference/query-dsl/nested-query/
  12. type NestedQuery struct {
  13. query Query
  14. filter Filter
  15. path string
  16. scoreMode string
  17. boost *float32
  18. queryName string
  19. }
  20. // Creates a new nested_query query.
  21. func NewNestedQuery(path string) NestedQuery {
  22. return NestedQuery{path: path}
  23. }
  24. func (q NestedQuery) Query(query Query) NestedQuery {
  25. q.query = query
  26. return q
  27. }
  28. func (q NestedQuery) Filter(filter Filter) NestedQuery {
  29. q.filter = filter
  30. return q
  31. }
  32. func (q NestedQuery) Path(path string) NestedQuery {
  33. q.path = path
  34. return q
  35. }
  36. func (q NestedQuery) ScoreMode(scoreMode string) NestedQuery {
  37. q.scoreMode = scoreMode
  38. return q
  39. }
  40. func (q NestedQuery) Boost(boost float32) NestedQuery {
  41. q.boost = &boost
  42. return q
  43. }
  44. func (q NestedQuery) QueryName(queryName string) NestedQuery {
  45. q.queryName = queryName
  46. return q
  47. }
  48. // Creates the query source for the nested_query query.
  49. func (q NestedQuery) Source() interface{} {
  50. // {
  51. // "nested" : {
  52. // "query" : {
  53. // "bool" : {
  54. // "must" : [
  55. // {
  56. // "match" : {"obj1.name" : "blue"}
  57. // },
  58. // {
  59. // "range" : {"obj1.count" : {"gt" : 5}}
  60. // }
  61. // ]
  62. // }
  63. // },
  64. // "filter" : {
  65. // ...
  66. // },
  67. // "path" : "obj1",
  68. // "score_mode" : "avg",
  69. // "boost" : 1.0
  70. // }
  71. // }
  72. query := make(map[string]interface{})
  73. nq := make(map[string]interface{})
  74. query["nested"] = nq
  75. if q.query != nil {
  76. nq["query"] = q.query.Source()
  77. }
  78. if q.filter != nil {
  79. nq["filter"] = q.filter.Source()
  80. }
  81. nq["path"] = q.path
  82. if q.scoreMode != "" {
  83. nq["score_mode"] = q.scoreMode
  84. }
  85. if q.boost != nil {
  86. nq["boost"] = *q.boost
  87. }
  88. if q.queryName != "" {
  89. nq["_name"] = q.queryName
  90. }
  91. return query
  92. }