Skip to content

Commit 95ebd30

Browse files
authored
Merge pull request #14 from NBZ4live/bulk_update
Improve Bulk class
2 parents 6d5842f + 7cc69c7 commit 95ebd30

File tree

1 file changed

+79
-4
lines changed

1 file changed

+79
-4
lines changed

src/Classes/Bulk.php

Lines changed: 79 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,14 +41,30 @@ class Bulk
4141
*/
4242
public $body = [];
4343

44+
/**
45+
* Number of pending operations
46+
* @var int
47+
*/
48+
public $operationCount = 0;
49+
50+
/**
51+
* Operation count which will trigger autocommit
52+
* @var int
53+
*/
54+
public $autocommitAfter = 0;
55+
4456

4557
/**
4658
* Bulk constructor.
4759
* @param Query $query
60+
* @param int $autocommitAfter
4861
*/
49-
public function __construct(Query $query)
62+
public function __construct(Query $query, $autocommitAfter = 0)
5063
{
64+
5165
$this->query = $query;
66+
$this->autocommitAfter = intval($autocommitAfter);
67+
5268
}
5369

5470
/**
@@ -125,26 +141,70 @@ public function id($_id = false)
125141
}
126142

127143
/**
128-
* Add pending document
144+
* Add pending document for insert
129145
* @param array $data
146+
* @return mixed
130147
*/
131148
public function insert($data = [])
132149
{
133150

151+
return $this->action('index', $data);
152+
153+
}
154+
155+
/**
156+
* Add pending document for update
157+
* @param array $data
158+
* @return mixed
159+
*/
160+
public function update($data = [])
161+
{
162+
163+
return $this->action('update', $data);
164+
165+
}
166+
167+
/**
168+
* Add pending document for deletion
169+
*/
170+
public function delete()
171+
{
172+
173+
return $this->action('delete');
174+
175+
}
176+
177+
/**
178+
* Add pending document abstract action
179+
* @param string $actionType
180+
* @param array $data
181+
* @return mixed
182+
*/
183+
public function action($actionType, $data = [])
184+
{
134185
$this->body["body"][] = [
135186

136-
'index' => [
187+
$actionType => [
137188
'_index' => $this->getIndex(),
138189
'_type' => $this->getType(),
139190
'_id' => $this->_id
140191
]
141192

142193
];
143194

144-
$this->body["body"][] = $data;
195+
if (!empty($data)) {
196+
$this->body["body"][] = $data;
197+
}
198+
199+
$this->operationCount++;
145200

146201
$this->reset();
147202

203+
if ($this->autocommitAfter > 0 && $this->operationCount >= $this->autocommitAfter) {
204+
return $this->commit();
205+
}
206+
207+
return true;
148208
}
149209

150210
/**
@@ -170,5 +230,20 @@ public function reset()
170230

171231
}
172232

233+
/**
234+
* Commit all pending operations
235+
*/
236+
public function commit()
237+
{
173238

239+
if (empty($this->body)) {
240+
return false;
241+
}
242+
243+
$result = $this->query->connection->bulk($this->body);
244+
$this->operationCount = 0;
245+
$this->body = [];
246+
247+
return $result;
248+
}
174249
}

0 commit comments

Comments
 (0)