search_queries_ids.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. // IdsQuery filters documents that only have the provided ids.
  6. // Note, this query uses the _uid field.
  7. //
  8. // For more details, see
  9. // https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-ids-query.html
  10. type IdsQuery struct {
  11. types []string
  12. values []string
  13. boost *float64
  14. queryName string
  15. }
  16. // NewIdsQuery creates and initializes a new ids query.
  17. func NewIdsQuery(types ...string) *IdsQuery {
  18. return &IdsQuery{
  19. types: types,
  20. values: make([]string, 0),
  21. }
  22. }
  23. // Ids adds ids to the filter.
  24. func (q *IdsQuery) Ids(ids ...string) *IdsQuery {
  25. q.values = append(q.values, ids...)
  26. return q
  27. }
  28. // Boost sets the boost for this query.
  29. func (q *IdsQuery) Boost(boost float64) *IdsQuery {
  30. q.boost = &boost
  31. return q
  32. }
  33. // QueryName sets the query name for the filter.
  34. func (q *IdsQuery) QueryName(queryName string) *IdsQuery {
  35. q.queryName = queryName
  36. return q
  37. }
  38. // Source returns JSON for the function score query.
  39. func (q *IdsQuery) Source() (interface{}, error) {
  40. // {
  41. // "ids" : {
  42. // "type" : "my_type",
  43. // "values" : ["1", "4", "100"]
  44. // }
  45. // }
  46. source := make(map[string]interface{})
  47. query := make(map[string]interface{})
  48. source["ids"] = query
  49. // type(s)
  50. if len(q.types) == 1 {
  51. query["type"] = q.types[0]
  52. } else if len(q.types) > 1 {
  53. query["types"] = q.types
  54. }
  55. // values
  56. query["values"] = q.values
  57. if q.boost != nil {
  58. query["boost"] = *q.boost
  59. }
  60. if q.queryName != "" {
  61. query["_name"] = q.queryName
  62. }
  63. return source, nil
  64. }