count.go 8.6 KB

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