bulk.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. "bytes"
  7. "context"
  8. "errors"
  9. "fmt"
  10. "net/url"
  11. "gopkg.in/olivere/elastic.v5/uritemplates"
  12. )
  13. // BulkService allows for batching bulk requests and sending them to
  14. // Elasticsearch in one roundtrip. Use the Add method with BulkIndexRequest,
  15. // BulkUpdateRequest, and BulkDeleteRequest to add bulk requests to a batch,
  16. // then use Do to send them to Elasticsearch.
  17. //
  18. // BulkService will be reset after each Do call. In other words, you can
  19. // reuse BulkService to send many batches. You do not have to create a new
  20. // BulkService for each batch.
  21. //
  22. // See https://www.elastic.co/guide/en/elasticsearch/reference/5.2/docs-bulk.html
  23. // for more details.
  24. type BulkService struct {
  25. client *Client
  26. index string
  27. typ string
  28. requests []BulkableRequest
  29. pipeline string
  30. timeout string
  31. refresh string
  32. routing string
  33. waitForActiveShards string
  34. pretty bool
  35. // estimated bulk size in bytes, up to the request index sizeInBytesCursor
  36. sizeInBytes int64
  37. sizeInBytesCursor int
  38. }
  39. // NewBulkService initializes a new BulkService.
  40. func NewBulkService(client *Client) *BulkService {
  41. builder := &BulkService{
  42. client: client,
  43. }
  44. return builder
  45. }
  46. func (s *BulkService) reset() {
  47. s.requests = make([]BulkableRequest, 0)
  48. s.sizeInBytes = 0
  49. s.sizeInBytesCursor = 0
  50. }
  51. // Index specifies the index to use for all batches. You may also leave
  52. // this blank and specify the index in the individual bulk requests.
  53. func (s *BulkService) Index(index string) *BulkService {
  54. s.index = index
  55. return s
  56. }
  57. // Type specifies the type to use for all batches. You may also leave
  58. // this blank and specify the type in the individual bulk requests.
  59. func (s *BulkService) Type(typ string) *BulkService {
  60. s.typ = typ
  61. return s
  62. }
  63. // Timeout is a global timeout for processing bulk requests. This is a
  64. // server-side timeout, i.e. it tells Elasticsearch the time after which
  65. // it should stop processing.
  66. func (s *BulkService) Timeout(timeout string) *BulkService {
  67. s.timeout = timeout
  68. return s
  69. }
  70. // Refresh controls when changes made by this request are made visible
  71. // to search. The allowed values are: "true" (refresh the relevant
  72. // primary and replica shards immediately), "wait_for" (wait for the
  73. // changes to be made visible by a refresh before applying), or "false"
  74. // (no refresh related actions).
  75. func (s *BulkService) Refresh(refresh string) *BulkService {
  76. s.refresh = refresh
  77. return s
  78. }
  79. // Routing specifies the routing value.
  80. func (s *BulkService) Routing(routing string) *BulkService {
  81. s.routing = routing
  82. return s
  83. }
  84. // Pipeline specifies the pipeline id to preprocess incoming documents with.
  85. func (s *BulkService) Pipeline(pipeline string) *BulkService {
  86. s.pipeline = pipeline
  87. return s
  88. }
  89. // WaitForActiveShards sets the number of shard copies that must be active
  90. // before proceeding with the bulk operation. Defaults to 1, meaning the
  91. // primary shard only. Set to `all` for all shard copies, otherwise set to
  92. // any non-negative value less than or equal to the total number of copies
  93. // for the shard (number of replicas + 1).
  94. func (s *BulkService) WaitForActiveShards(waitForActiveShards string) *BulkService {
  95. s.waitForActiveShards = waitForActiveShards
  96. return s
  97. }
  98. // Pretty tells Elasticsearch whether to return a formatted JSON response.
  99. func (s *BulkService) Pretty(pretty bool) *BulkService {
  100. s.pretty = pretty
  101. return s
  102. }
  103. // Add adds bulkable requests, i.e. BulkIndexRequest, BulkUpdateRequest,
  104. // and/or BulkDeleteRequest.
  105. func (s *BulkService) Add(requests ...BulkableRequest) *BulkService {
  106. for _, r := range requests {
  107. s.requests = append(s.requests, r)
  108. }
  109. return s
  110. }
  111. // EstimatedSizeInBytes returns the estimated size of all bulkable
  112. // requests added via Add.
  113. func (s *BulkService) EstimatedSizeInBytes() int64 {
  114. if s.sizeInBytesCursor == len(s.requests) {
  115. return s.sizeInBytes
  116. }
  117. for _, r := range s.requests[s.sizeInBytesCursor:] {
  118. s.sizeInBytes += s.estimateSizeInBytes(r)
  119. s.sizeInBytesCursor++
  120. }
  121. return s.sizeInBytes
  122. }
  123. // estimateSizeInBytes returns the estimates size of the given
  124. // bulkable request, i.e. BulkIndexRequest, BulkUpdateRequest, and
  125. // BulkDeleteRequest.
  126. func (s *BulkService) estimateSizeInBytes(r BulkableRequest) int64 {
  127. lines, _ := r.Source()
  128. size := 0
  129. for _, line := range lines {
  130. // +1 for the \n
  131. size += len(line) + 1
  132. }
  133. return int64(size)
  134. }
  135. // NumberOfActions returns the number of bulkable requests that need to
  136. // be sent to Elasticsearch on the next batch.
  137. func (s *BulkService) NumberOfActions() int {
  138. return len(s.requests)
  139. }
  140. func (s *BulkService) bodyAsString() (string, error) {
  141. var buf bytes.Buffer
  142. for _, req := range s.requests {
  143. source, err := req.Source()
  144. if err != nil {
  145. return "", err
  146. }
  147. for _, line := range source {
  148. buf.WriteString(line)
  149. buf.WriteByte('\n')
  150. }
  151. }
  152. return buf.String(), nil
  153. }
  154. // Do sends the batched requests to Elasticsearch. Note that, when successful,
  155. // you can reuse the BulkService for the next batch as the list of bulk
  156. // requests is cleared on success.
  157. func (s *BulkService) Do(ctx context.Context) (*BulkResponse, error) {
  158. // No actions?
  159. if s.NumberOfActions() == 0 {
  160. return nil, errors.New("elastic: No bulk actions to commit")
  161. }
  162. // Get body
  163. body, err := s.bodyAsString()
  164. if err != nil {
  165. return nil, err
  166. }
  167. // Build url
  168. path := "/"
  169. if len(s.index) > 0 {
  170. index, err := uritemplates.Expand("{index}", map[string]string{
  171. "index": s.index,
  172. })
  173. if err != nil {
  174. return nil, err
  175. }
  176. path += index + "/"
  177. }
  178. if len(s.typ) > 0 {
  179. typ, err := uritemplates.Expand("{type}", map[string]string{
  180. "type": s.typ,
  181. })
  182. if err != nil {
  183. return nil, err
  184. }
  185. path += typ + "/"
  186. }
  187. path += "_bulk"
  188. // Parameters
  189. params := make(url.Values)
  190. if s.pretty {
  191. params.Set("pretty", fmt.Sprintf("%v", s.pretty))
  192. }
  193. if s.pipeline != "" {
  194. params.Set("pipeline", s.pipeline)
  195. }
  196. if s.refresh != "" {
  197. params.Set("refresh", s.refresh)
  198. }
  199. if s.routing != "" {
  200. params.Set("routing", s.routing)
  201. }
  202. if s.timeout != "" {
  203. params.Set("timeout", s.timeout)
  204. }
  205. if s.waitForActiveShards != "" {
  206. params.Set("wait_for_active_shards", s.waitForActiveShards)
  207. }
  208. // Get response
  209. res, err := s.client.PerformRequest(ctx, "POST", path, params, body)
  210. if err != nil {
  211. return nil, err
  212. }
  213. // Return results
  214. ret := new(BulkResponse)
  215. if err := s.client.decoder.Decode(res.Body, ret); err != nil {
  216. return nil, err
  217. }
  218. // Reset so the request can be reused
  219. s.reset()
  220. return ret, nil
  221. }
  222. // BulkResponse is a response to a bulk execution.
  223. //
  224. // Example:
  225. // {
  226. // "took":3,
  227. // "errors":false,
  228. // "items":[{
  229. // "index":{
  230. // "_index":"index1",
  231. // "_type":"tweet",
  232. // "_id":"1",
  233. // "_version":3,
  234. // "status":201
  235. // }
  236. // },{
  237. // "index":{
  238. // "_index":"index2",
  239. // "_type":"tweet",
  240. // "_id":"2",
  241. // "_version":3,
  242. // "status":200
  243. // }
  244. // },{
  245. // "delete":{
  246. // "_index":"index1",
  247. // "_type":"tweet",
  248. // "_id":"1",
  249. // "_version":4,
  250. // "status":200,
  251. // "found":true
  252. // }
  253. // },{
  254. // "update":{
  255. // "_index":"index2",
  256. // "_type":"tweet",
  257. // "_id":"2",
  258. // "_version":4,
  259. // "status":200
  260. // }
  261. // }]
  262. // }
  263. type BulkResponse struct {
  264. Took int `json:"took,omitempty"`
  265. Errors bool `json:"errors,omitempty"`
  266. Items []map[string]*BulkResponseItem `json:"items,omitempty"`
  267. }
  268. // BulkResponseItem is the result of a single bulk request.
  269. type BulkResponseItem struct {
  270. Index string `json:"_index,omitempty"`
  271. Type string `json:"_type,omitempty"`
  272. Id string `json:"_id,omitempty"`
  273. Version int64 `json:"_version,omitempty"`
  274. Status int `json:"status,omitempty"`
  275. Result string `json:"result,omitempty"`
  276. ForcedRefresh bool `json:"forced_refresh,omitempty"`
  277. Found bool `json:"found,omitempty"`
  278. Error *ErrorDetails `json:"error,omitempty"`
  279. }
  280. // Indexed returns all bulk request results of "index" actions.
  281. func (r *BulkResponse) Indexed() []*BulkResponseItem {
  282. return r.ByAction("index")
  283. }
  284. // Created returns all bulk request results of "create" actions.
  285. func (r *BulkResponse) Created() []*BulkResponseItem {
  286. return r.ByAction("create")
  287. }
  288. // Updated returns all bulk request results of "update" actions.
  289. func (r *BulkResponse) Updated() []*BulkResponseItem {
  290. return r.ByAction("update")
  291. }
  292. // Deleted returns all bulk request results of "delete" actions.
  293. func (r *BulkResponse) Deleted() []*BulkResponseItem {
  294. return r.ByAction("delete")
  295. }
  296. // ByAction returns all bulk request results of a certain action,
  297. // e.g. "index" or "delete".
  298. func (r *BulkResponse) ByAction(action string) []*BulkResponseItem {
  299. if r.Items == nil {
  300. return nil
  301. }
  302. var items []*BulkResponseItem
  303. for _, item := range r.Items {
  304. if result, found := item[action]; found {
  305. items = append(items, result)
  306. }
  307. }
  308. return items
  309. }
  310. // ById returns all bulk request results of a given document id,
  311. // regardless of the action ("index", "delete" etc.).
  312. func (r *BulkResponse) ById(id string) []*BulkResponseItem {
  313. if r.Items == nil {
  314. return nil
  315. }
  316. var items []*BulkResponseItem
  317. for _, item := range r.Items {
  318. for _, result := range item {
  319. if result.Id == id {
  320. items = append(items, result)
  321. }
  322. }
  323. }
  324. return items
  325. }
  326. // Failed returns those items of a bulk response that have errors,
  327. // i.e. those that don't have a status code between 200 and 299.
  328. func (r *BulkResponse) Failed() []*BulkResponseItem {
  329. if r.Items == nil {
  330. return nil
  331. }
  332. var errors []*BulkResponseItem
  333. for _, item := range r.Items {
  334. for _, result := range item {
  335. if !(result.Status >= 200 && result.Status <= 299) {
  336. errors = append(errors, result)
  337. }
  338. }
  339. }
  340. return errors
  341. }
  342. // Succeeded returns those items of a bulk response that have no errors,
  343. // i.e. those have a status code between 200 and 299.
  344. func (r *BulkResponse) Succeeded() []*BulkResponseItem {
  345. if r.Items == nil {
  346. return nil
  347. }
  348. var succeeded []*BulkResponseItem
  349. for _, item := range r.Items {
  350. for _, result := range item {
  351. if result.Status >= 200 && result.Status <= 299 {
  352. succeeded = append(succeeded, result)
  353. }
  354. }
  355. }
  356. return succeeded
  357. }