1_0/Bulk.pm untested

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