multi_search.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. import (
  6. "encoding/json"
  7. "fmt"
  8. "net/url"
  9. "strings"
  10. )
  11. // MultiSearch executes one or more searches in one roundtrip.
  12. // See http://www.elasticsearch.org/guide/reference/api/multi-search/
  13. type MultiSearchService struct {
  14. client *Client
  15. requests []*SearchRequest
  16. indices []string
  17. pretty bool
  18. routing string
  19. preference string
  20. }
  21. func NewMultiSearchService(client *Client) *MultiSearchService {
  22. builder := &MultiSearchService{
  23. client: client,
  24. requests: make([]*SearchRequest, 0),
  25. indices: make([]string, 0),
  26. }
  27. return builder
  28. }
  29. func (s *MultiSearchService) Add(requests ...*SearchRequest) *MultiSearchService {
  30. s.requests = append(s.requests, requests...)
  31. return s
  32. }
  33. func (s *MultiSearchService) Index(index string) *MultiSearchService {
  34. s.indices = append(s.indices, index)
  35. return s
  36. }
  37. func (s *MultiSearchService) Indices(indices ...string) *MultiSearchService {
  38. s.indices = append(s.indices, indices...)
  39. return s
  40. }
  41. func (s *MultiSearchService) Pretty(pretty bool) *MultiSearchService {
  42. s.pretty = pretty
  43. return s
  44. }
  45. func (s *MultiSearchService) Do() (*MultiSearchResult, error) {
  46. // Build url
  47. path := "/_msearch"
  48. // Parameters
  49. params := make(url.Values)
  50. if s.pretty {
  51. params.Set("pretty", fmt.Sprintf("%v", s.pretty))
  52. }
  53. // Set body
  54. lines := make([]string, 0)
  55. for _, sr := range s.requests {
  56. // Set default indices if not specified in the request
  57. if !sr.HasIndices() && len(s.indices) > 0 {
  58. sr = sr.Indices(s.indices...)
  59. }
  60. header, err := json.Marshal(sr.header())
  61. if err != nil {
  62. return nil, err
  63. }
  64. body, err := json.Marshal(sr.body())
  65. if err != nil {
  66. return nil, err
  67. }
  68. lines = append(lines, string(header))
  69. lines = append(lines, string(body))
  70. }
  71. body := strings.Join(lines, "\n") + "\n" // Don't forget trailing \n
  72. // Get response
  73. res, err := s.client.PerformRequest("GET", path, params, body)
  74. if err != nil {
  75. return nil, err
  76. }
  77. // Return result
  78. ret := new(MultiSearchResult)
  79. if err := json.Unmarshal(res.Body, ret); err != nil {
  80. return nil, err
  81. }
  82. return ret, nil
  83. }
  84. type MultiSearchResult struct {
  85. Responses []*SearchResult `json:"responses,omitempty"`
  86. }