You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

search_queries_boosting.go 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // A boosting query can be used to effectively
  6. // demote results that match a given query.
  7. // For more details, see:
  8. // https://www.elastic.co/guide/en/elasticsearch/reference/7.0/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{}, error) {
  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. src, err := q.positiveClause.Source()
  61. if err != nil {
  62. return nil, err
  63. }
  64. boostingClause["positive"] = src
  65. }
  66. // negative
  67. if q.negativeClause != nil {
  68. src, err := q.negativeClause.Source()
  69. if err != nil {
  70. return nil, err
  71. }
  72. boostingClause["negative"] = src
  73. }
  74. if q.negativeBoost != nil {
  75. boostingClause["negative_boost"] = *q.negativeBoost
  76. }
  77. if q.boost != nil {
  78. boostingClause["boost"] = *q.boost
  79. }
  80. return query, nil
  81. }