search_queries_constant_score.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. // ConstantScoreQuery is a query that wraps a filter and simply returns
  6. // a constant score equal to the query boost for every document in the filter.
  7. //
  8. // For more details, see:
  9. // https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-constant-score-query.html
  10. type ConstantScoreQuery struct {
  11. filter Query
  12. boost *float64
  13. }
  14. // ConstantScoreQuery creates and initializes a new constant score query.
  15. func NewConstantScoreQuery(filter Query) *ConstantScoreQuery {
  16. return &ConstantScoreQuery{
  17. filter: filter,
  18. }
  19. }
  20. // Boost sets the boost for this query. Documents matching this query
  21. // will (in addition to the normal weightings) have their score multiplied
  22. // by the boost provided.
  23. func (q *ConstantScoreQuery) Boost(boost float64) *ConstantScoreQuery {
  24. q.boost = &boost
  25. return q
  26. }
  27. // Source returns the query source.
  28. func (q *ConstantScoreQuery) Source() (interface{}, error) {
  29. // "constant_score" : {
  30. // "filter" : {
  31. // ....
  32. // },
  33. // "boost" : 1.5
  34. // }
  35. query := make(map[string]interface{})
  36. params := make(map[string]interface{})
  37. query["constant_score"] = params
  38. // filter
  39. src, err := q.filter.Source()
  40. if err != nil {
  41. return nil, err
  42. }
  43. params["filter"] = src
  44. // boost
  45. if q.boost != nil {
  46. params["boost"] = *q.boost
  47. }
  48. return query, nil
  49. }