bulk.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. "bytes"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "net/url"
  11. "github.com/olivere/elastic/uritemplates"
  12. )
  13. type BulkService struct {
  14. client *Client
  15. index string
  16. _type string
  17. requests []BulkableRequest
  18. //replicationType string
  19. //consistencyLevel string
  20. timeout string
  21. refresh *bool
  22. pretty bool
  23. }
  24. func NewBulkService(client *Client) *BulkService {
  25. builder := &BulkService{
  26. client: client,
  27. requests: make([]BulkableRequest, 0),
  28. }
  29. return builder
  30. }
  31. func (s *BulkService) reset() {
  32. s.requests = make([]BulkableRequest, 0)
  33. }
  34. func (s *BulkService) Index(index string) *BulkService {
  35. s.index = index
  36. return s
  37. }
  38. func (s *BulkService) Type(_type string) *BulkService {
  39. s._type = _type
  40. return s
  41. }
  42. func (s *BulkService) Timeout(timeout string) *BulkService {
  43. s.timeout = timeout
  44. return s
  45. }
  46. func (s *BulkService) Refresh(refresh bool) *BulkService {
  47. s.refresh = &refresh
  48. return s
  49. }
  50. func (s *BulkService) Pretty(pretty bool) *BulkService {
  51. s.pretty = pretty
  52. return s
  53. }
  54. func (s *BulkService) Add(r BulkableRequest) *BulkService {
  55. s.requests = append(s.requests, r)
  56. return s
  57. }
  58. func (s *BulkService) NumberOfActions() int {
  59. return len(s.requests)
  60. }
  61. func (s *BulkService) bodyAsString() (string, error) {
  62. buf := bytes.NewBufferString("")
  63. for _, req := range s.requests {
  64. source, err := req.Source()
  65. if err != nil {
  66. return "", err
  67. }
  68. for _, line := range source {
  69. _, err := buf.WriteString(fmt.Sprintf("%s\n", line))
  70. if err != nil {
  71. return "", nil
  72. }
  73. }
  74. }
  75. return buf.String(), nil
  76. }
  77. func (s *BulkService) Do() (*BulkResponse, error) {
  78. // No actions?
  79. if s.NumberOfActions() == 0 {
  80. return nil, errors.New("elastic: No bulk actions to commit")
  81. }
  82. // Get body
  83. body, err := s.bodyAsString()
  84. if err != nil {
  85. return nil, err
  86. }
  87. // Build url
  88. path := "/"
  89. if s.index != "" {
  90. index, err := uritemplates.Expand("{index}", map[string]string{
  91. "index": s.index,
  92. })
  93. if err != nil {
  94. return nil, err
  95. }
  96. path += index + "/"
  97. }
  98. if s._type != "" {
  99. typ, err := uritemplates.Expand("{type}", map[string]string{
  100. "type": s._type,
  101. })
  102. if err != nil {
  103. return nil, err
  104. }
  105. path += typ + "/"
  106. }
  107. path += "_bulk"
  108. // Parameters
  109. params := make(url.Values)
  110. if s.pretty {
  111. params.Set("pretty", fmt.Sprintf("%v", s.pretty))
  112. }
  113. if s.refresh != nil {
  114. params.Set("refresh", fmt.Sprintf("%v", *s.refresh))
  115. }
  116. if s.timeout != "" {
  117. params.Set("timeout", s.timeout)
  118. }
  119. // Get response
  120. res, err := s.client.PerformRequest("POST", path, params, body)
  121. if err != nil {
  122. return nil, err
  123. }
  124. // Return results
  125. ret := new(BulkResponse)
  126. if err := json.Unmarshal(res.Body, ret); err != nil {
  127. return nil, err
  128. }
  129. // Reset so the request can be reused
  130. s.reset()
  131. return ret, nil
  132. }
  133. // BulkResponse is a response to a bulk execution.
  134. //
  135. // Example:
  136. // {
  137. // "took":3,
  138. // "errors":false,
  139. // "items":[{
  140. // "index":{
  141. // "_index":"index1",
  142. // "_type":"tweet",
  143. // "_id":"1",
  144. // "_version":3,
  145. // "status":201
  146. // }
  147. // },{
  148. // "index":{
  149. // "_index":"index2",
  150. // "_type":"tweet",
  151. // "_id":"2",
  152. // "_version":3,
  153. // "status":200
  154. // }
  155. // },{
  156. // "delete":{
  157. // "_index":"index1",
  158. // "_type":"tweet",
  159. // "_id":"1",
  160. // "_version":4,
  161. // "status":200,
  162. // "found":true
  163. // }
  164. // },{
  165. // "update":{
  166. // "_index":"index2",
  167. // "_type":"tweet",
  168. // "_id":"2",
  169. // "_version":4,
  170. // "status":200
  171. // }
  172. // }]
  173. // }
  174. type BulkResponse struct {
  175. Took int `json:"took,omitempty"`
  176. Errors bool `json:"errors,omitempty"`
  177. Items []map[string]*BulkResponseItem `json:"items,omitempty"`
  178. }
  179. // BulkResponseItem is the result of a single bulk request.
  180. type BulkResponseItem struct {
  181. Index string `json:"_index,omitempty"`
  182. Type string `json:"_type,omitempty"`
  183. Id string `json:"_id,omitempty"`
  184. Version int `json:"_version,omitempty"`
  185. Status int `json:"status,omitempty"`
  186. Found bool `json:"found,omitempty"`
  187. Error string `json:"error,omitempty"`
  188. }
  189. // Indexed returns all bulk request results of "index" actions.
  190. func (r *BulkResponse) Indexed() []*BulkResponseItem {
  191. return r.ByAction("index")
  192. }
  193. // Created returns all bulk request results of "create" actions.
  194. func (r *BulkResponse) Created() []*BulkResponseItem {
  195. return r.ByAction("create")
  196. }
  197. // Updated returns all bulk request results of "update" actions.
  198. func (r *BulkResponse) Updated() []*BulkResponseItem {
  199. return r.ByAction("update")
  200. }
  201. // Deleted returns all bulk request results of "delete" actions.
  202. func (r *BulkResponse) Deleted() []*BulkResponseItem {
  203. return r.ByAction("delete")
  204. }
  205. // ByAction returns all bulk request results of a certain action,
  206. // e.g. "index" or "delete".
  207. func (r *BulkResponse) ByAction(action string) []*BulkResponseItem {
  208. if r.Items == nil {
  209. return nil
  210. }
  211. items := make([]*BulkResponseItem, 0)
  212. for _, item := range r.Items {
  213. if result, found := item[action]; found {
  214. items = append(items, result)
  215. }
  216. }
  217. return items
  218. }
  219. // ById returns all bulk request results of a given document id,
  220. // regardless of the action ("index", "delete" etc.).
  221. func (r *BulkResponse) ById(id string) []*BulkResponseItem {
  222. if r.Items == nil {
  223. return nil
  224. }
  225. items := make([]*BulkResponseItem, 0)
  226. for _, item := range r.Items {
  227. for _, result := range item {
  228. if result.Id == id {
  229. items = append(items, result)
  230. }
  231. }
  232. }
  233. return items
  234. }
  235. // Failed returns those items of a bulk response that have errors,
  236. // i.e. those that don't have a status code between 200 and 299.
  237. func (r *BulkResponse) Failed() []*BulkResponseItem {
  238. if r.Items == nil {
  239. return nil
  240. }
  241. errors := make([]*BulkResponseItem, 0)
  242. for _, item := range r.Items {
  243. for _, result := range item {
  244. if !(result.Status >= 200 && result.Status <= 299) {
  245. errors = append(errors, result)
  246. }
  247. }
  248. }
  249. return errors
  250. }
  251. // Succeeded returns those items of a bulk response that have no errors,
  252. // i.e. those have a status code between 200 and 299.
  253. func (r *BulkResponse) Succeeded() []*BulkResponseItem {
  254. if r.Items == nil {
  255. return nil
  256. }
  257. succeeded := make([]*BulkResponseItem, 0)
  258. for _, item := range r.Items {
  259. for _, result := range item {
  260. if result.Status >= 200 && result.Status <= 299 {
  261. succeeded = append(succeeded, result)
  262. }
  263. }
  264. }
  265. return succeeded
  266. }