Debian Codegraph @

count.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 "fmt"
10 "net/url"
11 "strconv"
12 "strings"
13
14 "gopkg.in/olivere/elastic.v5/uritemplates"
15 )
16
17 // CountService is a convenient service for determining the
18 // number of documents in an index. Use SearchService with
19 // a SearchType of count for counting with queries etc.
20 type CountService struct {
21 client *Client
22 pretty bool
23 index []string
24 typ []string
25 allowNoIndices *bool
26 analyzeWildcard *bool
27 analyzer string
28 defaultOperator string
29 df string
30 expandWildcards string
31 ignoreUnavailable *bool
32 lenient *bool
33 lowercaseExpandedTerms *bool
34 minScore interface{}
35 preference string
36 q string
37 query Query
38 routing string
39 terminateAfter *int
40 bodyJson interface{}
41 bodyString string
42 }
43
44 // NewCountService creates a new CountService.
45 func NewCountService(client *Client) *CountService {
46 return &CountService{
47 client: client,
48 }
49 }
50
51 // Index sets the names of the indices to restrict the results.
52 func (s *CountService) Index(index ...string) *CountService {
53 if s.index == nil {
54 s.index = make([]string, 0)
55 }
56 s.index = append(s.index, index...)
57 return s
58 }
59
60 // Type sets the types to use to restrict the results.
61 func (s *CountService) Type(typ ...string) *CountService {
62 if s.typ == nil {
63 s.typ = make([]string, 0)
64 }
65 s.typ = append(s.typ, typ...)
66 return s
67 }
68
69 // AllowNoIndices indicates whether to ignore if a wildcard indices
70 // expression resolves into no concrete indices. (This includes "_all" string
71 // or when no indices have been specified).
72 func (s *CountService) AllowNoIndices(allowNoIndices bool) *CountService {
73 s.allowNoIndices = &allowNoIndices
74 return s
75 }
76
77 // AnalyzeWildcard specifies whether wildcard and prefix queries should be
78 // analyzed (default: false).
79 func (s *CountService) AnalyzeWildcard(analyzeWildcard bool) *CountService {
80 s.analyzeWildcard = &analyzeWildcard
81 return s
82 }
83
84 // Analyzer specifies the analyzer to use for the query string.
85 func (s *CountService) Analyzer(analyzer string) *CountService {
86 s.analyzer = analyzer
87 return s
88 }
89
90 // DefaultOperator specifies the default operator for query string query (AND or OR).
91 func (s *CountService) DefaultOperator(defaultOperator string) *CountService {
92 s.defaultOperator = defaultOperator
93 return s
94 }
95
96 // Df specifies the field to use as default where no field prefix is given
97 // in the query string.
98 func (s *CountService) Df(df string) *CountService {
99 s.df = df
100 return s
101 }
102
103 // ExpandWildcards indicates whether to expand wildcard expression to
104 // concrete indices that are open, closed or both.
105 func (s *CountService) ExpandWildcards(expandWildcards string) *CountService {
106 s.expandWildcards = expandWildcards
107 return s
108 }
109
110 // IgnoreUnavailable indicates whether specified concrete indices should be
111 // ignored when unavailable (missing or closed).
112 func (s *CountService) IgnoreUnavailable(ignoreUnavailable bool) *CountService {
113 s.ignoreUnavailable = &ignoreUnavailable
114 return s
115 }
116
117 // Lenient specifies whether format-based query failures (such as
118 // providing text to a numeric field) should be ignored.
119 func (s *CountService) Lenient(lenient bool) *CountService {
120 s.lenient = &lenient
121 return s
122 }
123
124 // LowercaseExpandedTerms specifies whether query terms should be lowercased.
125 func (s *CountService) LowercaseExpandedTerms(lowercaseExpandedTerms bool) *CountService {
126 s.lowercaseExpandedTerms = &lowercaseExpandedTerms
127 return s
128 }
129
130 // MinScore indicates to include only documents with a specific `_score`
131 // value in the result.
132 func (s *CountService) MinScore(minScore interface{}) *CountService {
133 s.minScore = minScore
134 return s
135 }
136
137 // Preference specifies the node or shard the operation should be
138 // performed on (default: random).
139 func (s *CountService) Preference(preference string) *CountService {
140 s.preference = preference
141 return s
142 }
143
144 // Q in the Lucene query string syntax. You can also use Query to pass
145 // a Query struct.
146 func (s *CountService) Q(q string) *CountService {
147 s.q = q
148 return s
149 }
150
151 // Query specifies the query to pass. You can also pass a query string with Q.
152 func (s *CountService) Query(query Query) *CountService {
153 s.query = query
154 return s
155 }
156
157 // Routing specifies the routing value.
158 func (s *CountService) Routing(routing string) *CountService {
159 s.routing = routing
160 return s
161 }
162
163 // TerminateAfter indicates the maximum count for each shard, upon reaching
164 // which the query execution will terminate early.
165 func (s *CountService) TerminateAfter(terminateAfter int) *CountService {
166 s.terminateAfter = &terminateAfter
167 return s
168 }
169
170 // Pretty indicates that the JSON response be indented and human readable.
171 func (s *CountService) Pretty(pretty bool) *CountService {
172 s.pretty = pretty
173 return s
174 }
175
176 // BodyJson specifies the query to restrict the results specified with the
177 // Query DSL (optional). The interface{} will be serialized to a JSON document,
178 // so use a map[string]interface{}.
179 func (s *CountService) BodyJson(body interface{}) *CountService {
180 s.bodyJson = body
181 return s
182 }
183
184 // Body specifies a query to restrict the results specified with
185 // the Query DSL (optional).
186 func (s *CountService) BodyString(body string) *CountService {
187 s.bodyString = body
188 return s
189 }
190
191 // buildURL builds the URL for the operation.
192 func (s *CountService) buildURL() (string, url.Values, error) {
193 var err error
194 var path string
195
196 if len(s.index) > 0 && len(s.typ) > 0 {
197 path, err = uritemplates.Expand("/{index}/{type}/_count", map[string]string{
198 "index": strings.Join(s.index, ","),
199 "type": strings.Join(s.typ, ","),
200 })
201 } else if len(s.index) > 0 {
202 path, err = uritemplates.Expand("/{index}/_count", map[string]string{
203 "index": strings.Join(s.index, ","),
204 })
205 } else if len(s.typ) > 0 {
206 path, err = uritemplates.Expand("/_all/{type}/_count", map[string]string{
207 "type": strings.Join(s.typ, ","),
208 })
209 } else {
210 path = "/_all/_count"
211 }
212 if err != nil {
213 return "", url.Values{}, err
214 }
215
216 // Add query string parameters
217 params := url.Values{}
218 if s.pretty {
219 params.Set("pretty", "1")
220 }
221 if s.allowNoIndices != nil {
222 params.Set("allow_no_indices", fmt.Sprintf("%v", *s.allowNoIndices))
223 }
224 if s.analyzeWildcard != nil {
225 params.Set("analyze_wildcard", fmt.Sprintf("%v", *s.analyzeWildcard))
226 }
227 if s.analyzer != "" {
228 params.Set("analyzer", s.analyzer)
229 }
230 if s.defaultOperator != "" {
231 params.Set("default_operator", s.defaultOperator)
232 }
233 if s.df != "" {
234 params.Set("df", s.df)
235 }
236 if s.expandWildcards != "" {
237 params.Set("expand_wildcards", s.expandWildcards)
238 }
239 if s.ignoreUnavailable != nil {
240 params.Set("ignore_unavailable", fmt.Sprintf("%v", *s.ignoreUnavailable))
241 }
242 if s.lenient != nil {
243 params.Set("lenient", fmt.Sprintf("%v", *s.lenient))
244 }
245 if s.lowercaseExpandedTerms != nil {
246 params.Set("lowercase_expanded_terms", fmt.Sprintf("%v", *s.lowercaseExpandedTerms))
247 }
248 if s.minScore != nil {
249 params.Set("min_score", fmt.Sprintf("%v", s.minScore))
250 }
251 if s.preference != "" {
252 params.Set("preference", s.preference)
253 }
254 if s.q != "" {
255 params.Set("q", s.q)
256 }
257 if s.routing != "" {
258 params.Set("routing", s.routing)
259 }
260 if s.terminateAfter != nil {
261 params.Set("terminate_after", strconv.Itoa(*s.terminateAfter))
262 }
263 return path, params, nil
264 }
265
266 // Validate checks if the operation is valid.
267 func (s *CountService) Validate() error {
268 return nil
269 }
270
271 // Do executes the operation.
272 func (s *CountService) Do(ctx context.Context) (int64, error) {
273 // Check pre-conditions
274 if err := s.Validate(); err != nil {
275 return 0, err
276 }
277
278 // Get URL for request
279 path, params, err := s.buildURL()
280 if err != nil {
281 return 0, err
282 }
283
284 // Setup HTTP request body
285 var body interface{}
286 if s.query != nil {
287 src, err := s.query.Source()
288 if err != nil {
289 return 0, err
290 }
291 query := make(map[string]interface{})
292 query["query"] = src
293 body = query
294 } else if s.bodyJson != nil {
295 body = s.bodyJson
296 } else if s.bodyString != "" {
297 body = s.bodyString
298 }
299
300 // Get HTTP response
301 res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
302 if err != nil {
303 return 0, err
304 }
305
306 // Return result
307 ret := new(CountResponse)
308 if err := s.client.decoder.Decode(res.Body, ret); err != nil {
309 return 0, err
310 }
311 if ret != nil {
312 return ret.Count, nil
313 }
314
315 return int64(0), nil
316 }
317
318 // CountResponse is the response of using the Count API.
319 type CountResponse struct {
320 Count int64 `json:"count"`
321 Shards *ShardsInfo `json:"_shards,omitempty"`
322 }