search_queries_dis_max.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 generates the union of documents produced by its subqueries,
  6. // and that scores each document with the maximum score for that document
  7. // as produced by any subquery, plus a tie breaking increment for
  8. // any additional matching subqueries.
  9. //
  10. // For more details, see:
  11. // http://www.elasticsearch.org/guide/reference/query-dsl/dis-max-query/
  12. type DisMaxQuery struct {
  13. queries []Query
  14. boost *float32
  15. tieBreaker *float32
  16. }
  17. // Creates a new dis_max query.
  18. func NewDisMaxQuery() DisMaxQuery {
  19. q := DisMaxQuery{
  20. queries: make([]Query, 0),
  21. }
  22. return q
  23. }
  24. func (q DisMaxQuery) Query(query Query) DisMaxQuery {
  25. q.queries = append(q.queries, query)
  26. return q
  27. }
  28. func (q DisMaxQuery) Boost(boost float32) DisMaxQuery {
  29. q.boost = &boost
  30. return q
  31. }
  32. func (q DisMaxQuery) TieBreaker(tieBreaker float32) DisMaxQuery {
  33. q.tieBreaker = &tieBreaker
  34. return q
  35. }
  36. // Creates the query source for the dis_max query.
  37. func (q DisMaxQuery) Source() interface{} {
  38. // {
  39. // "dis_max" : {
  40. // "tie_breaker" : 0.7,
  41. // "boost" : 1.2,
  42. // "queries" : {
  43. // {
  44. // "term" : { "age" : 34 }
  45. // },
  46. // {
  47. // "term" : { "age" : 35 }
  48. // }
  49. // ]
  50. // }
  51. // }
  52. query := make(map[string]interface{})
  53. disMax := make(map[string]interface{})
  54. query["dis_max"] = disMax
  55. // tieBreaker
  56. if q.tieBreaker != nil {
  57. disMax["tie_breaker"] = *q.tieBreaker
  58. }
  59. // boost
  60. if q.boost != nil {
  61. disMax["boost"] = *q.boost
  62. }
  63. // queries
  64. clauses := make([]interface{}, 0)
  65. for _, subQuery := range q.queries {
  66. clauses = append(clauses, subQuery.Source())
  67. }
  68. disMax["queries"] = clauses
  69. return query
  70. }