File: Scroll.pm

package info (click to toggle)
libsearch-elasticsearch-perl 8.12-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,372 kB
  • sloc: perl: 10,641; makefile: 2
file content (393 lines) | stat: -rw-r--r-- 10,990 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

package Search::Elasticsearch::Client::8_0::Scroll;
$Search::Elasticsearch::Client::8_0::Scroll::VERSION = '8.12';
use Moo;
use Search::Elasticsearch::Util qw(parse_params throw);
use namespace::clean;

has '_buffer' => ( is => 'ro' );

with 'Search::Elasticsearch::Role::Is_Sync',
    'Search::Elasticsearch::Client::8_0::Role::Scroll';

#===================================
sub BUILDARGS {
#===================================
    my ( $class, $params ) = parse_params(@_);
    my $es = delete $params->{es};
    my $scroll = $params->{scroll} ||= '1m';

    my $results      = $es->search($params);

    my $total = $results->{hits}{total};
    if (ref $total) {
        $total = $total->{value}
    }

    return {
        es           => $es,
        scroll       => $scroll,
        aggregations => $results->{aggregations},
        facets       => $results->{facets},
        suggest      => $results->{suggest},
        took         => $results->{took},
        total_took   => $results->{took},
        total        => $total,
        max_score    => $results->{hits}{max_score},
        _buffer      => $results->{hits}{hits},
        $total
        ? ( _scroll_id => $results->{_scroll_id} )
        : ( is_finished => 1 )
    };
}

#===================================
sub next {
#===================================
    my ( $self, $n ) = @_;
    $n ||= 1;
    while ( $self->_has_scroll_id and $self->buffer_size < $n ) {
        $self->refill_buffer;
    }
    my @return = splice( @{ $self->_buffer }, 0, $n );
    $self->finish if @return < $n;
    return wantarray ? @return : $return[-1];
}

#===================================
sub drain_buffer {
#===================================
    my $self = shift;
    return splice( @{ $self->_buffer } );
}

#===================================
sub buffer_size { 0 + @{ shift->_buffer } }
#===================================

#===================================
sub refill_buffer {
#===================================
    my $self = shift;

    return 0 if $self->is_finished;

    my $buffer    = $self->_buffer;
    my $scroll_id = $self->_scroll_id
        || return 0 + @$buffer;

    my $results = $self->scroll_request;

    my $hits = $results->{hits}{hits};
    $self->_set_total_took( $self->total_took + $results->{took} );

    if ( @$hits == 0 ) {
        $self->_clear_scroll_id;
    }
    else {
        $self->_set__scroll_id( $results->{_scroll_id} );
        push @$buffer, @$hits;
    }
    $self->finish if @$buffer == 0;
    return 0 + @$buffer;
}

#===================================
sub finish {
#===================================
    my $self = shift;
    return if $self->is_finished || $self->_pid != $$;

    $self->_set_is_finished(1);
    @{ $self->_buffer } = ();

    my $scroll_id = $self->_scroll_id or return;
    $self->_clear_scroll_id;

    my %args = ( body => { scroll_id => $scroll_id } );
    eval { $self->es->clear_scroll(%args) };
    return 1;
}

1;

=pod

=encoding UTF-8

=head1 NAME

Search::Elasticsearch::Client::8_0::Scroll - A helper module for scrolled searches

=head1 VERSION

version 8.12

=head1 SYNOPSIS

    use Search::Elasticsearch;

    my $es     = Search::Elasticsearch->new;

    my $scroll = $es->scroll_helper(
        index       => 'my_index',
        body => {
            query   => {...},
            size    => 1000,
            sort    => '_doc'
        }
    );

    say "Total hits: ". $scroll->total;

    while (my $doc = $scroll->next) {
        # do something
    }

=head1 DESCRIPTION

A I<scrolled search> is a search that allows you to keep pulling results
until there are no more matching results, much like a cursor in an SQL
database.

Unlike paginating through results (with the C<from> parameter in
L<search()|Search::Elasticsearch::Client::8_0::Direct/search()>),
scrolled searches take a snapshot of the current state of the index. Even
if you keep adding new documents to the index or updating existing documents,
a scrolled search will only see the index as it was when the search began.

This module is a helper utility that wraps the functionality of the
L<search()|Search::Elasticsearch::Client::8_0::Direct/search()> and
L<scroll()|Search::Elasticsearch::Client::8_0::Direct/scroll()> methods to make
them easier to use.

This class does L<Search::Elasticsearch::Client::8_0::Role::Scroll> and
L<Search::Elasticsearch::Role::Is_Sync>.

=head1 USE CASES

There are two primary use cases:

=head2 Pulling enough results

Perhaps you want to group your results by some field, and you don't know
exactly how many results you will need in order to return 10 grouped
results.  With a scrolled search you can keep pulling more results
until you have enough.  For instance, you can search emails in a mailing
list, and return results grouped by C<thread_id>:

    my (%groups,@results);

    my $scroll = $es->scroll_helper(
        index => 'my_emails',
        type  => 'email',
        body  => { query => {... some query ... }}
    );

    my $doc;
    while (@results < 10 and $doc = $scroll->next) {

        my $thread = $doc->{_source}{thread_id};

        unless ($groups{$thread}) {
            $groups{$thread} = [];
            push @results, $groups{$thread};
        }
        push @{$groups{$thread}},$doc;

    }

=head2 Extracting all documents

Often you will want to extract all (or a subset of) documents in an index.
If you want to change your type mappings, you will need to reindex all of your
data. Or perhaps you want to move a subset of the data in one index into
a new dedicated index. In these cases, you don't care about sort
order, you just want to retrieve all documents which match a query, and do
something with them. For instance, to retrieve all the docs for a particular
C<client_id>:

    my $scroll = $es->scroll_helper(
        index       => 'my_index',
        size        => 1000,
        body        => {
            query => {
                match => {
                    client_id => 123
                }
            },
            sort => '_doc'
        }
    );

    while (my $doc = $scroll->next) {
        # do something
    }

Very often the I<something> that you will want to do with these results
involves bulk-indexing them into a new index. The easiest way to
do this is to use the built-in L<Search::Elasticsearch::Client::8_0::Direct/reindex()>
functionality provided by Elasticsearch.

=head1 METHODS

=head2 C<new()>

    use Search::Elasticsearch;

    my $es = Search::Elasticsearch->new(...);
    my $scroll = $es->scroll_helper(
        scroll         => '1m',            # optional
        %search_params
    );

The L<Search::Elasticsearch::Client::8_0::Direct/scroll_helper()> method loads
L<Search::Elasticsearch::Client::8_0::Scroll> class and calls L</new()>,
passing in any arguments.

You can specify a C<scroll> duration (which defaults to C<"1m">).
Any other parameters are passed directly to L<Search::Elasticsearch::Client::8_0::Direct/search()>.

The C<scroll> duration tells Elasticearch how long it should keep the scroll
alive.  B<Note>: this duration doesn't need to be long enough to process
all results, just long enough to process a single B<batch> of results.
The expiry gets renewed for another C<scroll> period every time new
a new batch of results is retrieved from the cluster.

By default, the C<scroll_id> is passed as the C<body> to the
L<scroll|Search::Elasticsearch::Client::8_0::Direct/scroll()> request.

The C<scroll> request uses C<GET> by default.  To use C<POST> instead,
set L<send_get_body_as|Search::Elasticsearch::Transport/send_get_body_as> to
C<POST>.

=head2 C<next()>

    $doc  = $scroll->next;
    @docs = $scroll->next($num);

The C<next()> method returns the next result, or the next C<$num> results
(pulling more results if required).  If all results have been exhausted,
it returns an empty list.

=head2 C<drain_buffer()>

    @docs = $scroll->drain_buffer;

The C<drain_buffer()> method returns all of the documents currently in the
buffer, without fetching any more from the cluster.

=head2 C<refill_buffer()>

    $total = $scroll->refill_buffer;

The C<refill_buffer()> method fetches the next batch of results from the
cluster, stores them in the buffer, and returns the total number of docs
currently in the buffer.

=head2 C<buffer_size()>

    $total = $scroll->buffer_size;

The C<buffer_size()> method returns the total number of docs currently in
the buffer.

=head2 C<finish()>

    $scroll->finish;

The C<finish()> method clears out the buffer, sets L</is_finished()> to C<true>
and tries to clear the C<scroll_id> on Elasticsearch.  This API is only
supported since v0.90.6, but the call to C<clear_scroll> is wrapped in an
C<eval> so the C<finish()> method can be safely called with any version
of Elasticsearch.

When the C<$scroll> instance goes out of scope, L</finish()> is called
automatically if required.

=head2 C<is_finished()>

    $bool = $scroll->is_finished;

A flag which returns C<true> if all results have been processed or
L</finish()> has been called.

=head1 INFO ACCESSORS

The information from the original search is returned via the following
accessors:

=head2 C<total>

The total number of documents that matched your query.

=head2 C<max_score>

The maximum score of any documents in your query.

=head2 C<aggregations>

Any aggregations that were specified, or C<undef>

=head2 C<facets>

Any facets that were specified, or C<undef>

=head2 C<suggest>

Any suggestions that were specified, or C<undef>

=head2 C<took>

How long the original search took, in milliseconds

=head2 C<took_total>

How long the original search plus all subsequent batches took, in milliseconds.

=head1 SEE ALSO

=over

=item * L<Search::Elasticsearch::Client::8_0::Direct/search()>

=item * L<Search::Elasticsearch::Client::8_0::Direct/scroll()>

=item * L<Search::Elasticsearch::Client::8_0::Direct/reindex()>

=back

=head1 AUTHOR

Enrico Zimuel <enrico.zimuel@elastic.co>

=head1 COPYRIGHT AND LICENSE

This software is Copyright (c) 2024 by Elasticsearch BV.

This is free software, licensed under:

  The Apache License, Version 2.0, January 2004

=cut

__END__

# ABSTRACT: A helper module for scrolled searches