Debian Codegraph @

msearch.go

raw
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
5 package elastic
6
7 import (
8 "context"
9 "encoding/json"
10 "fmt"
11 "net/url"
12 "strings"
13 )
14
15 // MultiSearch executes one or more searches in one roundtrip.
16 type MultiSearchService struct {
17 client *Client
18 requests []*SearchRequest
19 indices []string
20 pretty bool
21 maxConcurrentRequests *int
22 preFilterShardSize *int
23 }
24
25 func NewMultiSearchService(client *Client) *MultiSearchService {
26 builder := &MultiSearchService{
27 client: client,
28 }
29 return builder
30 }
31
32 func (s *MultiSearchService) Add(requests ...*SearchRequest) *MultiSearchService {
33 s.requests = append(s.requests, requests...)
34 return s
35 }
36
37 func (s *MultiSearchService) Index(indices ...string) *MultiSearchService {
38 s.indices = append(s.indices, indices...)
39 return s
40 }
41
42 func (s *MultiSearchService) Pretty(pretty bool) *MultiSearchService {
43 s.pretty = pretty
44 return s
45 }
46
47 func (s *MultiSearchService) MaxConcurrentSearches(max int) *MultiSearchService {
48 s.maxConcurrentRequests = &max
49 return s
50 }
51
52 func (s *MultiSearchService) PreFilterShardSize(size int) *MultiSearchService {
53 s.preFilterShardSize = &size
54 return s
55 }
56
57 func (s *MultiSearchService) Do(ctx context.Context) (*MultiSearchResult, error) {
58 // Build url
59 path := "/_msearch"
60
61 // Parameters
62 params := make(url.Values)
63 if s.pretty {
64 params.Set("pretty", fmt.Sprintf("%v", s.pretty))
65 }
66 if v := s.maxConcurrentRequests; v != nil {
67 params.Set("max_concurrent_searches", fmt.Sprintf("%v", *v))
68 }
69 if v := s.preFilterShardSize; v != nil {
70 params.Set("pre_filter_shard_size", fmt.Sprintf("%v", *v))
71 }
72
73 // Set body
74 var lines []string
75 for _, sr := range s.requests {
76 // Set default indices if not specified in the request
77 if !sr.HasIndices() && len(s.indices) > 0 {
78 sr = sr.Index(s.indices...)
79 }
80
81 header, err := json.Marshal(sr.header())
82 if err != nil {
83 return nil, err
84 }
85 body, err := sr.Body()
86 if err != nil {
87 return nil, err
88 }
89 lines = append(lines, string(header))
90 lines = append(lines, body)
91 }
92 body := strings.Join(lines, "\n") + "\n" // add trailing \n
93
94 // Get response
95 res, err := s.client.PerformRequest(ctx, "GET", path, params, body)
96 if err != nil {
97 return nil, err
98 }
99
100 // Return result
101 ret := new(MultiSearchResult)
102 if err := s.client.decoder.Decode(res.Body, ret); err != nil {
103 return nil, err
104 }
105 return ret, nil
106 }
107
108 // MultiSearchResult is the outcome of running a multi-search operation.
109 type MultiSearchResult struct {
110 Responses []*SearchResult `json:"responses,omitempty"`
111 }