0_90/Scroll.pm untested

filter: Statementstmt 0.0% 0 / 59 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 14 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 114 CC 10 SCAR 24.0
CC
10
Cov
0%
refill_buffer
20.0
BUILDARGS
12.0
next
12.0
CRAP 11.0
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::0_90::Scroll;
6 $Search::Elasticsearch::Client::0_90::Scroll::VERSION = '7.30_1'; # TRIAL
7  
8 $Search::Elasticsearch::Client::0_90::Scroll::VERSION = '7.301';
9 use Moo;
10 use Search::Elasticsearch::Util qw(parse_params throw);
11 use namespace::clean;
12  
13 has '_buffer' => ( is => 'ro' );
14  
15 with 'Search::Elasticsearch::Role::Is_Sync',
16 'Search::Elasticsearch::Client::0_90::Role::Scroll';
17  
18 #===================================
19 sub BUILDARGS {
20 #===================================
21 my ( $class, $params ) = parse_params(@_);
22 my $es = delete $params->{es};
23 my $scroll = $params->{scroll} ||= '1m';
24  
25 throw( 'Param',
26 'The (scroll_in_body) parameter has been replaced by (scroll_in_qs)' )
27 if exists $params->{scroll_in_body};
28  
29 my $scroll_in_qs = delete $params->{scroll_in_qs};
30 my $results = $es->search($params);
31  
32 my $total = $results->{hits}{total};
33  
34 return {
35 es => $es,
36 scroll => $scroll,
37 scroll_in_qs => $scroll_in_qs,
38 aggregations => $results->{aggregations},
39 facets => $results->{facets},
40 suggest => $results->{suggest},
41 took => $results->{took},
42 total_took => $results->{took},
43 total => $total,
44 max_score => $results->{hits}{max_score},
45 _buffer => $results->{hits}{hits},
46 $total
47 ? ( _scroll_id => $results->{_scroll_id} )
48 : ( is_finished => 1 )
49 };
50 }
51  
52 #===================================
53 sub next {
54 #===================================
55 my ( $self, $n ) = @_;
56 $n ||= 1;
57 while ( $self->_has_scroll_id and $self->buffer_size < $n ) {
58 $self->refill_buffer;
59 }
60 my @return = splice( @{ $self->_buffer }, 0, $n );
61 $self->finish if @return < $n;
62 return wantarray ? @return : $return[-1];
63 }
64  
65 #===================================
66 sub drain_buffer {
67 #===================================
68 my $self = shift;
69 return splice( @{ $self->_buffer } );
70 }
71  
72 #===================================
73 sub buffer_size { 0 + @{ shift->_buffer } }
74 #===================================
75  
76 #===================================
77 sub refill_buffer {
78 #===================================
79 my $self = shift;
80  
81 return 0 if $self->is_finished;
82  
83 my $buffer = $self->_buffer;
84 my $scroll_id = $self->_scroll_id
85 || return 0 + @$buffer;
86  
87 my $results = $self->scroll_request;
88  
89 my $hits = $results->{hits}{hits};
90 $self->_set_total_took( $self->total_took + $results->{took} );
91  
92 if ( @$hits == 0 ) {
93 $self->_clear_scroll_id;
94 }
95 else {
96 $self->_set__scroll_id( $results->{_scroll_id} );
97 push @$buffer, @$hits;
98 }
99 $self->finish if @$buffer == 0;
100 return 0 + @$buffer;
101 }
102  
103 #===================================
104 sub finish {
105 #===================================
106 my $self = shift;
107 return if $self->is_finished || $self->_pid != $$;
108  
109 $self->_set_is_finished(1);
110 @{ $self->_buffer } = ();
111  
112 my $scroll_id = $self->_scroll_id or return;
113 $self->_clear_scroll_id;
114  
115 my %args
116 = $self->scroll_in_qs
117 ? ( scroll_id => $scroll_id )
118 : ( body => $scroll_id );
119 eval { $self->es->clear_scroll(%args) };
120 return 1;
121 }
122  
123 1;
124  
125 =pod
126  
127 =encoding UTF-8
128  
129 =head1 NAME
130  
131 Search::Elasticsearch::Client::0_90::Scroll - A helper module for scrolled searches
132  
133 =head1 VERSION
134  
135 version 7.30_1
136  
137 =head1 SYNOPSIS
138  
139 use Search::Elasticsearch;
140  
141 my $es = Search::Elasticsearch->new;
142  
143 my $scroll = $es->scroll_helper(
144 index => 'my_index',
145 search_type => 'scan',
146 size => 500
147 );
148  
149 say "Total hits: ". $scroll->total;
150  
151 while (my $doc = $scroll->next) {
152 # do something
153 }
154  
155 =head1 DESCRIPTION
156  
157 A I<scrolled search> is a search that allows you to keep pulling results
158 until there are no more matching results, much like a cursor in an SQL
159 database.
160  
161 Unlike paginating through results (with the C<from> parameter in
162 L<search()|Search::Elasticsearch::Client::0_90::Direct/search()>),
163 scrolled searches take a snapshot of the current state of the index. Even
164 if you keep adding new documents to the index or updating existing documents,
165 a scrolled search will only see the index as it was when the search began.
166  
167 This module is a helper utility that wraps the functionality of the
168 L<search()|Search::Elasticsearch::Client::0_90::Direct/search()> and
169 L<scroll()|Search::Elasticsearch::Client::0_90::Direct/scroll()> methods to make
170 them easier to use.
171  
172 B<IMPORTANT>: Deep scrolling can be expensive. See L</DEEP SCROLLING>
173 for more.
174  
175 This class does L<Search::Elasticsearch::Client::0_90::Role::Scroll> and
176 L<Search::Elasticsearch::Role::Is_Sync>.
177  
178 =head1 USE CASES
179  
180 There are two primary use cases:
181  
182 =head2 Pulling enough results
183  
184 Perhaps you want to group your results by some field, and you don't know
185 exactly how many results you will need in order to return 10 grouped
186 results. With a scrolled search you can keep pulling more results
187 until you have enough. For instance, you can search emails in a mailing
188 list, and return results grouped by C<thread_id>:
189  
190 my (%groups,@results);
191  
192 my $scroll = $es->scroll_helper(
193 index => 'my_emails',
194 type => 'email',
195 body => { query => {... some query ... }}
196 );
197  
198 my $doc;
199 while (@results < 10 and $doc = $scroll->next) {
200  
201 my $thread = $doc->{_source}{thread_id};
202  
203 unless ($groups{$thread}) {
204 $groups{$thread} = [];
205 push @results, $groups{$thread};
206 }
207 push @{$groups{$thread}},$doc;
208  
209 }
210  
211 =head2 Extracting all documents
212  
213 Often you will want to extract all (or a subset of) documents in an index.
214 If you want to change your type mappings, you will need to reindex all of your
215 data. Or perhaps you want to move a subset of the data in one index into
216 a new dedicated index. In these cases, you don't care about sort
217 order, you just want to retrieve all documents which match a query, and do
218 something with them. For instance, to retrieve all the docs for a particular
219 C<client_id>:
220  
221 my $scroll = $es->scroll_helper(
222 index => 'my_index',
223 search_type => 'scan', # important!
224 size => 500,
225 body => {
226 query => {
227 match => {
228 client_id => 123
229 }
230 }
231 }
232 );
233  
234 while (my $doc = $scroll->next) {
235 # do something
236 }
237  
238 Very often the I<something> that you will want to do with these results
239 involves bulk-indexing them into a new index. The easiest way to
240 marry a scrolled search with bulk indexing is to use the
241 L<Search::Elasticsearch::Client::0_90::Bulk/reindex()> method.
242  
243 =head1 DEEP SCROLLING
244  
245 Deep scrolling (and deep pagination) are very expensive in a distributed
246 environment, and the reason they are expensive is that results need to
247 be sorted in a global order.
248  
249 For example, if we have an index with 5 shards, and we request the first
250 10 results, each shard has to return its top 10, and then the I<requesting
251 node> (the node that is handling the search request) has to resort these
252 50 results to return a global top 10. Now, if we request page 1,000
253 (ie results 10,001 .. 10,010), then each shard has to return 10,010 results,
254 and the requesting node has to sort through 50,050 results just to return
255 10 of them!
256  
257 You can see how this can get very heavy very quickly. This is the reason that
258 web search engines never return more than 1,000 results.
259  
260 =head2 Disable sorting for efficient scrolling
261  
262 The problem with deep scrolling is the sorting phase. If we disable sorting,
263 then we can happily scroll through millions of documents efficiently. The
264 way to do this is to set C<search_type> to C<scan>:
265  
266 my $scroll = $es->scroll_helper(
267 search_type => 'scan',
268 size => 500,
269 );
270  
271 Scanning disables sorting and will just return C<size> results from each
272 shard until there are no more results to return. B<Note>: this means
273 that, when querying an index with 5 shards, the scrolled search
274 will pull C<size * 5> results at a time. If you have large documents or
275 are memory constrained, you will need to take this into account.
276  
277 =head1 METHODS
278  
279 =head2 C<new()>
280  
281 use Search::Elasticsearch;
282  
283 my $es = Search::Elasticsearch->new(...);
284 my $scroll = $es->scroll_helper(
285 scroll => '1m', # optional
286 scroll_in_qs => 0|1, # optional
287 %search_params
288 );
289  
290 The L<Search::Elasticsearch::Client::0_90::Direct/scroll_helper()> method loads
291 L<Search::Elasticsearch::Client::0_90::Scroll> class and calls L</new()>,
292 passing in any arguments.
293  
294 You can specify a C<scroll> duration (which defaults to C<"1m">) and
295 C<scroll_in_qs> (which defaults to C<false>). Any other parameters are
296 passed directly to L<Search::Elasticsearch::Client::0_90::Direct/search()>.
297  
298 The C<scroll> duration tells Elasticearch how long it should keep the scroll
299 alive. B<Note>: this duration doesn't need to be long enough to process
300 all results, just long enough to process a single B<batch> of results.
301 The expiry gets renewed for another C<scroll> period every time new
302 a new batch of results is retrieved from the cluster.
303  
304 By default, the C<scroll_id> is passed as the C<body> to the
305 L<scroll|Search::Elasticsearch::Client::0_90::Direct/scroll()> request.
306 To send it in the query string instead, set C<scroll_in_qs> to a true value,
307 but be aware: when querying very many indices, the scroll ID can become
308 too long for intervening proxies.
309  
310 The C<scroll> request uses C<GET> by default. To use C<POST> instead,
311 set L<send_get_body_as|Search::Elasticsearch::Transport/send_get_body_as> to
312 C<POST>.
313  
314 =head2 C<next()>
315  
316 $doc = $scroll->next;
317 @docs = $scroll->next($num);
318  
319 The C<next()> method returns the next result, or the next C<$num> results
320 (pulling more results if required). If all results have been exhausted,
321 it returns an empty list.
322  
323 =head2 C<drain_buffer()>
324  
325 @docs = $scroll->drain_buffer;
326  
327 The C<drain_buffer()> method returns all of the documents currently in the
328 buffer, without fetching any more from the cluster.
329  
330 =head2 C<refill_buffer()>
331  
332 $total = $scroll->refill_buffer;
333  
334 The C<refill_buffer()> method fetches the next batch of results from the
335 cluster, stores them in the buffer, and returns the total number of docs
336 currently in the buffer.
337  
338 =head2 C<buffer_size()>
339  
340 $total = $scroll->buffer_size;
341  
342 The C<buffer_size()> method returns the total number of docs currently in
343 the buffer.
344  
345 =head2 C<finish()>
346  
347 $scroll->finish;
348  
349 The C<finish()> method clears out the buffer, sets L</is_finished()> to C<true>
350 and tries to clear the C<scroll_id> on Elasticsearch. This API is only
351 supported since v0.90.5, but the call to C<clear_scroll> is wrapped in an
352 C<eval> so the C<finish()> method can be safely called with any version
353 of Elasticsearch.
354  
355 When the C<$scroll> instance goes out of scope, L</finish()> is called
356 automatically if required.
357  
358 =head2 C<is_finished()>
359  
360 $bool = $scroll->is_finished;
361  
362 A flag which returns C<true> if all results have been processed or
363 L</finish()> has been called.
364  
365 =head1 INFO ACCESSORS
366  
367 The information from the original search is returned via the following
368 accessors:
369  
370 =head2 C<total>
371  
372 The total number of documents that matched your query.
373  
374 =head2 C<max_score>
375  
376 The maximum score of any documents in your query.
377  
378 =head2 C<aggregations>
379  
380 Any aggregations that were specified, or C<undef>
381  
382 =head2 C<facets>
383  
384 Any facets that were specified, or C<undef>
385  
386 =head2 C<suggest>
387  
388 Any suggestions that were specified, or C<undef>
389  
390 =head2 C<took>
391  
392 How long the original search took, in milliseconds
393  
394 =head2 C<took_total>
395  
396 How long the original search plus all subsequent batches took, in milliseconds.
397  
398 =head1 SEE ALSO
399  
400 =over
401  
402 =item * L<Search::Elasticsearch::Client::0_90::Bulk/reindex()>
403  
404 =item * L<Search::Elasticsearch::Client::0_90::Direct/search()>
405  
406 =item * L<Search::Elasticsearch::Client::0_90::Direct/scroll()>
407  
408 =back
409  
410 =head1 AUTHOR
411  
412 Enrico Zimuel <enrico.zimuel@elastic.co>
413  
414 =head1 COPYRIGHT AND LICENSE
415  
416 This software is Copyright (c) 2020 by Elasticsearch BV.
417  
418 This is free software, licensed under:
419  
420 The Apache License, Version 2.0, January 2004
421  
422 =cut
423  
424 __END__