search_queries_boosting.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 boosting query can be used to effectively
  6. // demote results that match a given query.
  7. // For more details, see:
  8. // http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-boosting-query.html
  9. type BoostingQuery struct {
  10. Query
  11. positiveClause Query
  12. negativeClause Query
  13. negativeBoost *float64
  14. boost *float64
  15. }
  16. // Creates a new boosting query.
  17. func NewBoostingQuery() BoostingQuery {
  18. return BoostingQuery{}
  19. }
  20. func (q BoostingQuery) Positive(positive Query) BoostingQuery {
  21. q.positiveClause = positive
  22. return q
  23. }
  24. func (q BoostingQuery) Negative(negative Query) BoostingQuery {
  25. q.negativeClause = negative
  26. return q
  27. }
  28. func (q BoostingQuery) NegativeBoost(negativeBoost float64) BoostingQuery {
  29. q.negativeBoost = &negativeBoost
  30. return q
  31. }
  32. func (q BoostingQuery) Boost(boost float64) BoostingQuery {
  33. q.boost = &boost
  34. return q
  35. }
  36. // Creates the query source for the boosting query.
  37. func (q BoostingQuery) Source() interface{} {
  38. // {
  39. // "boosting" : {
  40. // "positive" : {
  41. // "term" : {
  42. // "field1" : "value1"
  43. // }
  44. // },
  45. // "negative" : {
  46. // "term" : {
  47. // "field2" : "value2"
  48. // }
  49. // },
  50. // "negative_boost" : 0.2
  51. // }
  52. // }
  53. query := make(map[string]interface{})
  54. boostingClause := make(map[string]interface{})
  55. query["boosting"] = boostingClause
  56. // Negative and positive clause as well as negative boost
  57. // are mandatory in the Java client.
  58. // positive
  59. if q.positiveClause != nil {
  60. boostingClause["positive"] = q.positiveClause.Source()
  61. }
  62. // negative
  63. if q.negativeClause != nil {
  64. boostingClause["negative"] = q.negativeClause.Source()
  65. }
  66. if q.negativeBoost != nil {
  67. boostingClause["negative_boost"] = *q.negativeBoost
  68. }
  69. if q.boost != nil {
  70. boostingClause["boost"] = *q.boost
  71. }
  72. return query
  73. }