1_0/Bulk.pm untested

filter: Statementstmt 0.0% 0 / 67 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 127 CC 9 SCAR 28.1
CC
9
Cov
0%
flush
30.0
reindex
20.0
add_action
6.0
CRAP 16.7
1 package Search::Elasticsearch::Client::1_0::Bulk;
2 $Search::Elasticsearch::Client::1_0::Bulk::VERSION = '6.81';
3 use Moo;
4 with 'Search::Elasticsearch::Client::1_0::Role::Bulk',
5 'Search::Elasticsearch::Role::Is_Sync';
6 use Search::Elasticsearch::Util qw(parse_params throw);
7 use Try::Tiny;
8 use namespace::clean;
9  
10 #===================================
11 sub add_action {
12 #===================================
13 my $self = shift;
14 my $buffer = $self->_buffer;
15 my $max_size = $self->max_size;
16 my $max_count = $self->max_count;
17 my $max_time = $self->max_time;
18  
19 while (@_) {
20 my @json = $self->_encode_action( splice( @_, 0, 2 ) );
21  
22 push @$buffer, @json;
23  
24 my $size = $self->_buffer_size;
25 $size += length($_) + 1 for @json;
26 $self->_buffer_size($size);
27  
28 my $count = $self->_buffer_count( $self->_buffer_count + 1 );
29  
30 $self->flush
31 if ( $max_size and $size >= $max_size )
32 || ( $max_count and $count >= $max_count )
33 || ( $max_time and time >= $self->_last_flush + $max_time );
34 }
35 return 1;
36 }
37  
38 #===================================
39 sub flush {
40 #===================================
41 my $self = shift;
42 $self->_last_flush(time);
43  
44 return { items => [] }
45 unless $self->_buffer_size;
46  
47 if ( $self->verbose ) {
48 local $| = 1;
49 print ".";
50 }
51 my $buffer = $self->_buffer;
52 my $results = try {
53 my $res = $self->es->bulk( %{ $self->_bulk_args }, body => $buffer );
54 $self->clear_buffer;
55 return $res;
56 }
57 catch {
58 my $error = $_;
59 $self->clear_buffer
60 unless $error->is( 'Cxn', 'NoNodes' );
61  
62 die $error;
63 };
64 $self->_report( $buffer, $results );
65 return defined wantarray ? $results : undef;
66 }
67  
68 #===================================
69 sub reindex {
70 #===================================
71 my ( $self, $params ) = parse_params(@_);
72 my $src = $params->{source}
73 or throw( 'Param', "Missing required param <source>" );
74  
75 my $transform = $self->_doc_transformer($params);
76  
77 if ( ref $src eq 'HASH' ) {
78 $src = {%$src};
79 my $es = delete $src->{es} || $self->es;
80 my %body
81 = $es->api_version ge '1_0'
82 ? ( sort => '_doc', size => 1000 )
83 : ( search_type => 'scan', size => 500 );
84 my $scroll = $es->scroll_helper(
85 %body, %$src
86 );
87  
88 $src = sub {
89 $scroll->refill_buffer;
90 $scroll->drain_buffer;
91 };
92  
93 print "Reindexing " . $scroll->total . " docs\n"
94 if $self->verbose;
95 }
96  
97 while ( my @docs = grep {defined} $src->() ) {
98 $self->index( grep {$_} map { $transform->($_) } @docs );
99 }
100 $self->flush;
101 return 1;
102 }
103  
104 1;
105  
106 =pod
107  
108 =encoding UTF-8
109  
110 =head1 NAME
111  
112 Search::Elasticsearch::Client::1_0::Bulk - A helper module for the Bulk API and for reindexing
113  
114 =head1 VERSION
115  
116 version 6.81
117  
118 =head1 SYNOPSIS
119  
120 use Search::Elasticsearch;
121  
122 my $es = Search::Elasticsearch->new;
123 my $bulk = $es->bulk_helper(
124 index => 'my_index',
125 type => 'my_type'
126 );
127  
128 # Index docs:
129 $bulk->index({ id => 1, source => { foo => 'bar' }});
130 $bulk->add_action( index => { id => 1, source => { foo=> 'bar' }});
131  
132 # Create docs:
133 $bulk->create({ id => 1, source => { foo => 'bar' }});
134 $bulk->add_action( create => { id => 1, source => { foo=> 'bar' }});
135 $bulk->create_docs({ foo => 'bar' })
136  
137 # Delete docs:
138 $bulk->delete({ id => 1});
139 $bulk->add_action( delete => { id => 1 });
140 $bulk->delete_ids(1,2,3)
141  
142 # Update docs:
143 $bulk->update({ id => 1, script => '...' });
144 $bulk->add_action( update => { id => 1, script => '...' });
145  
146 # Manual flush
147 $bulk->flush;
148  
149 # Reindex docs:
150 my $bulk = $es->bulk_helper(
151 index => 'new_index',
152 verbose => 1
153 );
154  
155 $bulk->reindex( source => { index => 'old_index' });
156  
157 =head1 DESCRIPTION
158  
159 This module provides a wrapper for the L<Search::Elasticsearch::Client::1_0::Direct/bulk()>
160 method which makes it easier to run multiple create, index, update or delete
161 actions in a single request. It also provides a simple interface
162 for L<reindexing documents|/REINDEXING DOCUMENTS>.
163  
164 The L<Search::Elasticsearch::Client::1_0::Bulk> module acts as a queue, buffering up actions
165 until it reaches a maximum count of actions, or a maximum size of JSON request
166 body, at which point it issues a C<bulk()> request.
167  
168 Once you have finished adding actions, call L</flush()> to force the final
169 C<bulk()> request on the items left in the queue.
170  
171 This class does L<Search::Elasticsearch::Client::1_0::Role::Bulk> and
172 L<Search::Elasticsearch::Role::Is_Sync>.
173  
174 =head1 CREATING A NEW INSTANCE
175  
176 =head2 C<new()>
177  
178 my $bulk = $es->bulk_helper(
179  
180 index => 'default_index', # optional
181 type => 'default_type', # optional
182 %other_bulk_params # optional
183  
184 max_count => 1_000, # optional
185 max_size => 1_000_000, # optional
186 max_time => 5, # optional
187  
188 verbose => 0 | 1, # optional
189  
190 on_success => sub {...}, # optional
191 on_error => sub {...}, # optional
192 on_conflict => sub {...}, # optional
193  
194  
195 );
196  
197 The C<new()> method returns a new C<$bulk> object. You must pass your
198 Search::Elasticsearch client as the C<es> argument.
199  
200 The C<index> and C<type> parameters provide default values for
201 C<index> and C<type>, which can be overridden in each action.
202 You can also pass any other values which are accepted
203 by the L<bulk()|Search::Elasticsearch::Client::1_0::Direct/bulk()> method.
204  
205 See L</flush()> for more information about the other parameters.
206  
207 =head1 FLUSHING THE BUFFER
208  
209 =head2 C<flush()>
210  
211 $result = $bulk->flush;
212  
213 The C<flush()> method sends all buffered actions to Elasticsearch using
214 a L<bulk()|Search::Elasticsearch::Client::1_0::Direct/bulk()> request.
215  
216 =head2 Auto-flushing
217  
218 An automatic L</flush()> is triggered whenever the C<max_count>, C<max_size>,
219 or C<max_time> threshold is breached. This causes all actions in the buffer to be
220 sent to Elasticsearch.
221  
222 =over
223  
224 =item * C<max_count>
225  
226 The maximum number of actions to allow before triggering a L</flush()>.
227 This can be disabled by setting C<max_count> to C<0>. Defaults to
228 C<1,000>.
229  
230 =item * C<max_size>
231  
232 The maximum size of JSON request body to allow before triggering a
233 L</flush()>. This can be disabled by setting C<max_size> to C<0>. Defaults
234 to C<1_000,000> bytes.
235  
236 =item * C<max_time>
237  
238 The maximum number of seconds to wait before triggering a flush. Defaults
239 to C<0> seconds, which means that it is disabled. B<Note:> This timeout
240 is only triggered when new items are added to the queue, not in the background.
241  
242 =back
243  
244 =head2 Errors when flushing
245  
246 There are two types of error which can be thrown when L</flush()>
247 is called, either manually or automatically.
248  
249 =over
250  
251 =item * Temporary Elasticsearch errors
252  
253 A C<Cxn> error like a C<NoNodes> error which indicates that your cluster is down.
254 These errors do not clear the buffer, as they can be retried later on.
255  
256 =item * Action errors
257  
258 Individual actions may fail. For instance, a C<create> action will fail
259 if a document with the same C<index>, C<type> and C<id> already exists.
260 These action errors are reported via L<callbacks|/Using callbacks>.
261  
262 =back
263  
264 =head2 Using callbacks
265  
266 By default, any I<Action errors> (see above) cause warnings to be
267 written to C<STDERR>. However, you can use the C<on_error>, C<on_conflict>
268 and C<on_success> callbacks for more fine-grained control.
269  
270 All callbacks receive the following arguments:
271  
272 =over
273  
274 =item C<$action>
275  
276 The name of the action, ie C<index>, C<create>, C<update> or C<delete>.
277  
278 =item C<$response>
279  
280 The response that Elasticsearch returned for this action.
281  
282 =item C<$i>
283  
284 The index of the action, ie the first action in the flush request
285 will have C<$i> set to C<0>, the second will have C<$i> set to C<1> etc.
286  
287 =back
288  
289 =head3 C<on_success>
290  
291 my $bulk = $es->bulk_helper(
292 on_success => sub {
293 my ($action,$response,$i) = @_;
294 # do something
295 },
296 );
297  
298 The C<on_success> callback is called for every action that has a successful
299 response.
300  
301 =head3 C<on_conflict>
302  
303 my $bulk = $es->bulk_helper(
304 on_conflict => sub {
305 my ($action,$response,$i,$version) = @_;
306 # do something
307 },
308 );
309  
310 The C<on_conflict> callback is called for actions that have triggered
311 a C<Conflict> error, eg trying to C<create> a document which already
312 exists. The C<$version> argument will contain the version number
313 of the document currently stored in Elasticsearch (if found).
314  
315 =head3 C<on_error>
316  
317 my $bulk = $es->bulk_helper(
318 on_error => sub {
319 my ($action,$response,$i) = @_;
320 # do something
321 },
322 );
323  
324 The C<on_error> callback is called for any error (unless the C<on_conflict>)
325 callback has already been called).
326  
327 =head2 Disabling callbacks and autoflush
328  
329 If you want to be in control of flushing, and you just want to receive
330 the raw response that Elasticsearch sends instead of using callbacks,
331 then you can do so as follows:
332  
333 my $bulk = $es->bulk_helper(
334 max_count => 0,
335 max_size => 0,
336 on_error => undef
337 );
338  
339 $bulk->add_actions(....);
340 $response = $bulk->flush;
341  
342 =head1 CREATE, INDEX, UPDATE, DELETE
343  
344 =head2 C<add_action()>
345  
346 $bulk->add_action(
347 create => { ...params... },
348 index => { ...params... },
349 update => { ...params... },
350 delete => { ...params... }
351 );
352  
353 The C<add_action()> method allows you to add multiple C<create>, C<index>,
354 C<update> and C<delete> actions to the queue. The first value is the action
355 type, and the second value is the parameters that describe that action.
356 See the individual helper methods below for details.
357  
358 B<Note:> Parameters like C<index> or C<type> can be specified as C<index> or as
359 C<_index>, so the following two lines are equivalent:
360  
361 index => { index => 'index', type => 'type', id => 1, source => {...}},
362 index => { _index => 'index', _type => 'type', _id => 1, _source => {...}},
363  
364 B<Note:> The C<index> and C<type> parameters can be specified in the
365 params for any action, but if not specified, will default to the C<index>
366 and C<type> values specified in L</new()>. These are required parameters:
367 they must be specified either in L</new()> or in every action.
368  
369 =head2 C<create()>
370  
371 $bulk->create(
372 { index => 'custom_index', source => { doc body }},
373 { type => 'custom_type', id => 1, source => { doc body }},
374 ...
375 );
376  
377 The C<create()> helper method allows you to add multiple C<create> actions.
378 It accepts the same parameters as L<Search::Elasticsearch::Client::1_0::Direct/create()>
379 except that the document body should be passed as the C<source> or C<_source>
380 parameter, instead of as C<body>.
381  
382 =head2 C<create_docs()>
383  
384 $bulk->create_docs(
385 { doc body },
386 { doc body },
387 ...
388 );
389  
390 The C<create_docs()> helper is a shorter form of L</create()> which can be used
391 when you are using the default C<index> and C<type> as set in L</new()>
392 and you are not specifying a custom C<id> per document. In this case,
393 you can just pass the individual document bodies.
394  
395 =head2 C<index()>
396  
397 $bulk->index(
398 { index => 'custom_index', source => { doc body }},
399 { type => 'custom_type', id => 1, source => { doc body }},
400 ...
401 );
402  
403 The C<index()> helper method allows you to add multiple C<index> actions.
404 It accepts the same parameters as L<Search::Elasticsearch::Client::1_0::Direct/index()>
405 except that the document body should be passed as the C<source> or C<_source>
406 parameter, instead of as C<body>.
407  
408 =head2 C<delete()>
409  
410 $bulk->delete(
411 { index => 'custom_index', id => 1},
412 { type => 'custom_type', id => 2},
413 ...
414 );
415  
416 The C<delete()> helper method allows you to add multiple C<delete> actions.
417 It accepts the same parameters as L<Search::Elasticsearch::Client::1_0::Direct/delete()>.
418  
419 =head2 C<delete_ids()>
420  
421 $bulk->delete_ids(1,2,3...)
422  
423 The C<delete_ids()> helper method can be used when all of the documents you
424 want to delete have the default C<index> and C<type> as set in L</new()>.
425 In this case, all you have to do is to pass in a list of IDs.
426  
427 =head2 C<update()>
428  
429 $bulk->update(
430 { id => 1,
431 doc => { partial doc },
432 doc_as_upsert => 1
433 },
434 { id => 2,
435 lang => 'mvel',
436 script => { script }
437 upsert => { upsert doc }
438 },
439 ...
440 );
441  
442 The C<update()> helper method allows you to add multiple C<update> actions.
443 It accepts the same parameters as L<Search::Elasticsearch::Client::1_0::Direct/update()>.
444 An update can either use a I<partial doc> which gets merged with an existing
445 doc (example 1 above), or can use a C<script> to update an existing doc
446 (example 2 above). More information on C<script> can be found here:
447 L<Search::Elasticsearch::Client::1_0::Direct/update()>.
448  
449 =head1 REINDEXING DOCUMENTS
450  
451 A common use case for bulk indexing is to reindex a whole index when
452 changing the type mappings or analysis chain. This typically
453 combines bulk indexing with L<scrolled searches|Search::Elasticsearch::Client::1_0::Scroll>:
454 the scrolled search pulls all of the data from the source index, and
455 the bulk indexer indexes the data into the new index.
456  
457 =head2 C<reindex()>
458  
459 $bulk->reindex(
460 source => $source, # required
461 transform => \&transform, # optional
462 version_type => 'external|internal', # optional
463 );
464  
465 The C<reindex()> method requires a C<$source> parameter, which provides
466 the source for the documents which are to be reindexed.
467  
468 =head2 Reindexing from another index
469  
470 If the C<source> argument is a HASH ref, then the hash is passed to
471 L<Search::Elasticsearch::Client::1_0::Scroll/new()> to create a new scrolled search.
472  
473 my $bulk = $es->bulk_helper(
474 index => 'new_index',
475 verbose => 1
476 );
477  
478 $bulk->reindex(
479 source => {
480 index => 'old_index',
481 size => 500, # default
482 search_type => 'scan' # default
483 }
484 );
485  
486 If a default C<index> or C<type> has been specified in the call to
487 L</new()>, then it will replace the C<index> and C<type> values for
488 the docs returned from the scrolled search. In the example above,
489 all docs will be retrieved from C<"old_index"> and will be bulk indexed
490 into C<"new_index">.
491  
492 =head2 Reindexing from a generic source
493  
494 The C<source> parameter also accepts a coderef or an anonymous sub,
495 which should return one or more new documents every time it is executed.
496 This allows you to pass any iterator, wrapped in an anonymous sub:
497  
498 my $iter = get_iterator_from_somewhere();
499  
500 $bulk->reindex(
501 source => sub { $iter->next }
502 );
503  
504 =head2 Transforming docs on the fly
505  
506 The C<transform> parameter allows you to change documents on the fly,
507 using a callback. The callback receives the document as the only argument,
508 and should return the updated document, or C<undef> if the document should
509 not be indexed:
510  
511 $bulk->reindex(
512 source => { index => 'old_index' },
513 transform => sub {
514 my $doc = shift;
515  
516 # don't index doc marked as valid:false
517 return undef unless $doc->{_source}{valid};
518  
519 # convert $tag to @tags
520 $doc->{_source}{tags} = [ delete $doc->{_source}{tag}];
521 return $doc
522 }
523 );
524  
525 =head2 Reindexing from another cluster
526  
527 By default, L</reindex()> expects the source and destination indices
528 to be in the same cluster. To pull data from one cluster and index it into
529 another, you can use two separate C<$es> objects:
530  
531 $es_target = Search::Elasticsearch->new( nodes => 'localhost:9200' );
532 $es_source = Search::Elasticsearch->new( nodes => 'search1:9200' );
533  
534 my $bulk = $es_targert->bulk_helper(
535 verbose => 1
536 )
537 -> reindex(
538 source => {
539 es => $es_source,
540 index => 'my_index'
541 }
542 );
543  
544 =head2 Parents and routing
545  
546 If you are using parent-child relationships or custom C<routing> values,
547 and you want to preserve these when you reindex your documents, then
548 you will need to request these values specifically, as follows:
549  
550 $bulk->reindex(
551 source => {
552 index => 'old_index',
553 fields => ['_source','_parent','_routing']
554 }
555 );
556  
557 =head2 Working with version numbers
558  
559 Every document in Elasticsearch has a current C<version> number, which
560 is used for L<optimistic concurrency control|http://en.wikipedia.org/wiki/Optimistic_concurrency_control>,
561 that is, to ensure that you don't overwrite changes that have been made
562 by another process.
563  
564 All CRUD operations accept a C<version> parameter and a C<version_type>
565 parameter which tells Elasticsearch that the change should only be made
566 if the current document corresponds to these parameters. The
567 C<version_type> parameter can have the following values:
568  
569 =over
570  
571 =item * C<internal>
572  
573 Use Elasticsearch version numbers. Documents are only changed if the
574 document in Elasticsearch has the B<same> C<version> number that is
575 specified in the CRUD operation. After the change, the new
576 version number is C<version+1>.
577  
578 =item * C<external>
579  
580 Use an external versioning system, such as timestamps or version numbers
581 from an external database. Documents are only changed if the document
582 in Elasticsearch has a B<lower> C<version> number than the one
583 specified in the CRUD operation. After the change, the new version
584 number is C<version>.
585  
586 =back
587  
588 If you would like to reindex documents from one index to another, preserving
589 the C<version> numbers from the original index, then you need the following:
590  
591 $bulk->reindex(
592 source => {
593 index => 'old_index',
594 version => 1, # retrieve version numbers in search
595 },
596 version_type => 'external' # use these "external" version numbers
597 );
598  
599 =head1 AUTHOR
600  
601 Enrico Zimuel <enrico.zimuel@elastic.co>
602  
603 =head1 COPYRIGHT AND LICENSE
604  
605 This software is Copyright (c) 2020 by Elasticsearch BV.
606  
607 This is free software, licensed under:
608  
609 The Apache License, Version 2.0, January 2004
610  
611 =cut
612  
613 __END__