search_queries_indices.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. // IndicesQuery can be used when executed across multiple indices, allowing
  6. // to have a query that executes only when executed on an index that matches
  7. // a specific list of indices, and another query that executes when it is
  8. // executed on an index that does not match the listed indices.
  9. //
  10. // For more details, see
  11. // https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-indices-query.html
  12. type IndicesQuery struct {
  13. query Query
  14. indices []string
  15. noMatchQueryType string
  16. noMatchQuery Query
  17. queryName string
  18. }
  19. // NewIndicesQuery creates and initializes a new indices query.
  20. func NewIndicesQuery(query Query, indices ...string) *IndicesQuery {
  21. return &IndicesQuery{
  22. query: query,
  23. indices: indices,
  24. }
  25. }
  26. // NoMatchQuery sets the query to use when it executes on an index that
  27. // does not match the indices provided.
  28. func (q *IndicesQuery) NoMatchQuery(query Query) *IndicesQuery {
  29. q.noMatchQuery = query
  30. return q
  31. }
  32. // NoMatchQueryType sets the no match query which can be either all or none.
  33. func (q *IndicesQuery) NoMatchQueryType(typ string) *IndicesQuery {
  34. q.noMatchQueryType = typ
  35. return q
  36. }
  37. // QueryName sets the query name for the filter.
  38. func (q *IndicesQuery) QueryName(queryName string) *IndicesQuery {
  39. q.queryName = queryName
  40. return q
  41. }
  42. // Source returns JSON for the function score query.
  43. func (q *IndicesQuery) Source() (interface{}, error) {
  44. // {
  45. // "indices" : {
  46. // "indices" : ["index1", "index2"],
  47. // "query" : {
  48. // "term" : { "tag" : "wow" }
  49. // },
  50. // "no_match_query" : {
  51. // "term" : { "tag" : "kow" }
  52. // }
  53. // }
  54. // }
  55. source := make(map[string]interface{})
  56. params := make(map[string]interface{})
  57. source["indices"] = params
  58. params["indices"] = q.indices
  59. src, err := q.query.Source()
  60. if err != nil {
  61. return nil, err
  62. }
  63. params["query"] = src
  64. if q.noMatchQuery != nil {
  65. src, err := q.noMatchQuery.Source()
  66. if err != nil {
  67. return nil, err
  68. }
  69. params["no_match_query"] = src
  70. } else if q.noMatchQueryType != "" {
  71. params["no_match_query"] = q.noMatchQueryType
  72. }
  73. if q.queryName != "" {
  74. params["_name"] = q.queryName
  75. }
  76. return source, nil
  77. }