Bug 18854: Protect few other occurrences of offset
[koha.git] / Koha / SearchEngine / Elasticsearch / Search.pm
1 package Koha::SearchEngine::Elasticsearch::Search;
2
3 # Copyright 2014 Catalyst IT
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 =head1 NAME
21
22 Koha::SearchEngine::Elasticsearch::Search - search functions for Elasticsearch
23
24 =head1 SYNOPSIS
25
26     my $searcher =
27       Koha::SearchEngine::Elasticsearch::Search->new( { index => $index } );
28     my $builder = Koha::SearchEngine::Elasticsearch::QueryBuilder->new(
29         { index => $index } );
30     my $query = $builder->build_query('perl');
31     my $results = $searcher->search($query);
32     print "There were " . $results->total . " results.\n";
33     $results->each(sub {
34         push @hits, @_[0];
35     });
36
37 =head1 METHODS
38
39 =cut
40
41 use Modern::Perl;
42
43 use base qw(Koha::SearchEngine::Elasticsearch);
44 use C4::Context;
45 use Koha::ItemTypes;
46 use Koha::AuthorisedValues;
47 use Koha::SearchEngine::QueryBuilder;
48 use Koha::SearchEngine::Search;
49 use MARC::Record;
50 use Catmandu::Store::ElasticSearch;
51
52 use Data::Dumper; #TODO remove
53 use Carp qw(cluck);
54
55 Koha::SearchEngine::Elasticsearch::Search->mk_accessors(qw( store ));
56
57 =head2 search
58
59     my $results = $searcher->search($query, $page, $count, %options);
60
61 Run a search using the query. It'll return C<$count> results, starting at page
62 C<$page> (C<$page> counts from 1, anything less that, or C<undef> becomes 1.)
63 C<$count> is also the number of entries on a page.
64
65 C<%options> is a hash containing extra options:
66
67 =over 4
68
69 =item offset
70
71 If provided, this overrides the C<$page> value, and specifies the record as
72 an offset (i.e. the number of the record to start with), rather than a page.
73
74 =back
75
76 Returns
77
78 =cut
79
80 sub search {
81     my ($self, $query, $page, $count, %options) = @_;
82
83     my $params = $self->get_elasticsearch_params();
84     my %paging;
85     # 20 is the default number of results per page
86     $paging{limit} = $count || 20;
87     # ES/Catmandu doesn't want pages, it wants a record to start from.
88     if (exists $options{offset}) {
89         $paging{start} = $options{offset};
90     } else {
91         $page = (!defined($page) || ($page <= 0)) ? 0 : $page - 1;
92         $paging{start} = $page * $paging{limit};
93     }
94     $self->store(
95         Catmandu::Store::ElasticSearch->new(
96             %$params,
97         )
98     ) unless $self->store;
99     my $results = eval {
100         $self->store->bag->search( %$query, %paging );
101     };
102     if ($@) {
103         die $self->process_error($@);
104     }
105     return $results;
106 }
107
108 =head2 count
109
110     my $count = $searcher->count($query);
111
112 This mimics a search request, but just gets the result count instead. That's
113 faster than pulling all the data in, usually.
114
115 =cut
116
117 sub count {
118     my ( $self, $query ) = @_;
119
120     my $params = $self->get_elasticsearch_params();
121     $self->store(
122         Catmandu::Store::ElasticSearch->new( %$params, trace_calls => 0, ) )
123       unless $self->store;
124
125     my $search = $self->store->bag->search( %$query);
126     my $count = $search->total() || 0;
127     return $count;
128 }
129
130 =head2 search_compat
131
132     my ( $error, $results, $facets ) = $search->search_compat(
133         $query,            $simple_query, \@sort_by,       \@servers,
134         $results_per_page, $offset,       $expanded_facet, $branches,
135         $query_type,       $scan
136       )
137
138 A search interface somewhat compatible with L<C4::Search->getRecords>. Anything
139 that is returned in the query created by build_query_compat will probably
140 get ignored here, along with some other things (like C<@servers>.)
141
142 =cut
143
144 sub search_compat {
145     my (
146         $self,     $query,            $simple_query, $sort_by,
147         $servers,  $results_per_page, $offset,       $expanded_facet,
148         $branches, $query_type,       $scan
149     ) = @_;
150     my %options;
151     $options{offset} = $offset;
152     $offset = 0 if $offset < 0;
153     $options{expanded_facet} = $expanded_facet;
154     my $results = $self->search($query, undef, $results_per_page, %options);
155
156     # Convert each result into a MARC::Record
157     my (@records, $index);
158     $index = $offset; # opac-search expects results to be put in the
159         # right place in the array, according to $offset
160     $results->each(sub {
161             # The results come in an array for some reason
162             my $marc_json = $_[0]->{record};
163             my $marc = $self->json2marc($marc_json);
164             $records[$index++] = $marc;
165         });
166     # consumers of this expect a name-spaced result, we provide the default
167     # configuration.
168     my %result;
169     $result{biblioserver}{hits} = $results->total;
170     $result{biblioserver}{RECORDS} = \@records;
171     return (undef, \%result, $self->_convert_facets($results->{aggregations}, $expanded_facet));
172 }
173
174 =head2 search_auth_compat
175
176     my ( $results, $total ) =
177       $searcher->search_auth_compat( $query, $page, $count, %options );
178
179 This has a similar calling convention to L<search>, however it returns its
180 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
181
182 =cut
183
184 sub search_auth_compat {
185     my $self = shift;
186
187     # TODO handle paging
188     my $database = Koha::Database->new();
189     my $schema   = $database->schema();
190     my $res      = $self->search(@_);
191     my $bib_searcher = Koha::SearchEngine::Elasticsearch::Search->new({index => 'biblios'});
192     my @records;
193     $res->each(
194         sub {
195             my %result;
196             my $record    = $_[0];
197             my $marc_json = $record->{record};
198
199             # I wonder if these should be real values defined in the mapping
200             # rather than hard-coded conversions.
201             # Our results often come through as nested arrays, to fix this
202             # requires changes in catmandu.
203             my $authid = $record->{ 'Local-number' }[0][0];
204             $result{authid} = $authid;
205
206             # TODO put all this info into the record at index time so we
207             # don't have to go and sort it all out now.
208             my $authtypecode = $record->{authtype};
209             my $rs           = $schema->resultset('AuthType')
210               ->search( { authtypecode => $authtypecode } );
211
212             # FIXME there's an assumption here that we will get a result.
213             # the original code also makes an assumption that some provided
214             # authtypecode may sometimes be used instead of the one stored
215             # with the record. It's not documented why this is the case, so
216             # it's not reproduced here yet.
217             my $authtype           = $rs->single;
218             my $auth_tag_to_report = $authtype->auth_tag_to_report;
219             my $marc               = $self->json2marc($marc_json);
220             my $mainentry          = $marc->field($auth_tag_to_report);
221             my $reported_tag;
222             if ($mainentry) {
223                 foreach ( $mainentry->subfields() ) {
224                     $reported_tag .= '$' . $_->[0] . $_->[1];
225                 }
226             }
227             # Turn the resultset into a hash
228             my %authtype_cols;
229             foreach my $col ($authtype->result_source->columns) {
230                 $authtype_cols{$col} = $authtype->get_column($col);
231             }
232             $result{authtype}     = $authtype->authtypetext;
233             $result{reported_tag} = $reported_tag;
234
235             # Reimplementing BuildSummary is out of scope because it'll be hard
236             $result{summary} =
237               C4::AuthoritiesMarc::BuildSummary( $marc, $result{authid},
238                 $authtypecode );
239             $result{used} = $self->count_auth_use($bib_searcher, $authid);
240             push @records, \%result;
241         }
242     );
243     return ( \@records, $res->total );
244 }
245
246 =head2 count_auth_use
247
248     my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
249
250 This runs a search to determine the number of records that reference the
251 specified authid. C<$bib_searcher> must be something compatible with
252 elasticsearch, as the query is built in this function.
253
254 =cut
255
256 sub count_auth_use {
257     my ($self, $bib_searcher, $authid) = @_;
258
259     my $query = {
260         query => {
261             bool => {
262 #                query  => { match_all => {} },
263                 filter => { term      => { an => $authid } }
264             }
265         }
266     };
267     $bib_searcher->count($query);
268 }
269
270 =head2 simple_search_compat
271
272     my ( $error, $marcresults, $total_hits ) =
273       $searcher->simple_search( $query, $offset, $max_results, %options );
274
275 This is a simpler interface to the searching, intended to be similar enough to
276 L<C4::Search::SimpleSearch>.
277
278 Arguments:
279
280 =over 4
281
282 =item C<$query>
283
284 A thing to search for. It could be a simple string, or something constructed
285 with the appropriate QueryBuilder module.
286
287 =item C<$offset>
288
289 How many results to skip from the start of the results.
290
291 =item C<$max_results>
292
293 The max number of results to return. The default is 100 (because unlimited
294 is a pretty terrible thing to do.)
295
296 =item C<%options>
297
298 These options are unused by Elasticsearch
299
300 =back
301
302 Returns:
303
304 =over 4
305
306 =item C<$error>
307
308 if something went wrong, this'll contain some kind of error
309 message.
310
311 =item C<$marcresults>
312
313 an arrayref of MARC::Records (note that this is different from the
314 L<C4::Search> version which will return plain XML, but too bad.)
315
316 =item C<$total_hits>
317
318 the total number of results that this search could have returned.
319
320 =back
321
322 =cut
323
324 sub simple_search_compat {
325     my ($self, $query, $offset, $max_results) = @_;
326
327     return ('No query entered', undef, undef) unless $query;
328
329     my %options;
330     $offset = 0 if not defined $offset or $offset < 0;
331     $options{offset} = $offset;
332     $max_results //= 100;
333
334     unless (ref $query) {
335         # We'll push it through the query builder to sanitise everything.
336         my $qb = Koha::SearchEngine::QueryBuilder->new({index => $self->index});
337         (undef,$query) = $qb->build_query_compat(undef, [$query]);
338     }
339     my $results = $self->search($query, undef, $max_results, %options);
340     my @records;
341     $results->each(sub {
342             # The results come in an array for some reason
343             my $marc_json = $_[0]->{record};
344             my $marc = $self->json2marc($marc_json);
345             push @records, $marc;
346         });
347     return (undef, \@records, $results->total);
348 }
349
350 =head2 extract_biblionumber
351
352     my $biblionumber = $searcher->extract_biblionumber( $searchresult );
353
354 $searchresult comes from simple_search_compat.
355
356 Returns the biblionumber from the search result record.
357
358 =cut
359
360 sub extract_biblionumber {
361     my ( $self, $searchresultrecord ) = @_;
362     return Koha::SearchEngine::Search::extract_biblionumber( $searchresultrecord );
363 }
364
365 =head2 json2marc
366
367     my $marc = $self->json2marc($marc_json);
368
369 Converts the form of marc (based on its JSON, but as a Perl structure) that
370 Catmandu stores into a MARC::Record object.
371
372 =cut
373
374 sub json2marc {
375     my ( $self, $marcjson ) = @_;
376
377     my $marc = MARC::Record->new();
378     $marc->encoding('UTF-8');
379
380     # fields are like:
381     # [ '245', '1', '2', 'a' => 'Title', 'b' => 'Subtitle' ]
382     # or
383     # [ '001', undef, undef, '_', 'a value' ]
384     # conveniently, this is the form that MARC::Field->new() likes
385     foreach my $field (@$marcjson) {
386         next if @$field < 5;
387         if ( $field->[0] eq 'LDR' ) {
388             $marc->leader( $field->[4] );
389         }
390         else {
391             my $tag = $field->[0];
392             my $marc_field;
393             if ( MARC::Field->is_controlfield_tag( $field->[0] ) ) {
394                 $marc_field = MARC::Field->new($field->[0], $field->[4]);
395             } else {
396                 $marc_field = MARC::Field->new(@$field);
397             }
398             $marc->append_fields($marc_field);
399         }
400     }
401     return $marc;
402 }
403
404 =head2 _convert_facets
405
406     my $koha_facets = _convert_facets($es_facets, $expanded_facet);
407
408 Converts elasticsearch facets types to the form that Koha expects.
409 It expects the ES facet name to match the Koha type, for example C<itype>,
410 C<au>, C<su-to>, etc.
411
412 C<$expanded_facet> is the facet that we want to show FacetMaxCount entries for, rather
413 than just 5 like normal.
414
415 =cut
416
417 sub _convert_facets {
418     my ( $self, $es, $exp_facet ) = @_;
419
420     return if !$es;
421
422     # These should correspond to the ES field names, as opposed to the CCL
423     # things that zebra uses.
424     # TODO let the library define the order using the interface.
425     my %type_to_label = (
426         author   => { order => 1, label => 'Authors', },
427         itype    => { order => 2, label => 'ItemTypes', },
428         location => { order => 3, label => 'Location', },
429         'su-geo' => { order => 4, label => 'Places', },
430         se       => { order => 5, label => 'Series', },
431         subject  => { order => 6, label => 'Topics', },
432         ccode    => { order => 7, label => 'CollectionCodes',},
433         holdingbranch => { order => 8, label => 'HoldingLibrary' },
434         homebranch => { order => 9, label => 'HomeLibrary' }
435     );
436
437     # We also have some special cases, e.g. itypes that need to show the
438     # value rather than the code.
439     my @itypes = Koha::ItemTypes->search;
440     my @libraries = Koha::Libraries->search;
441     my $library_names = { map { $_->branchcode => $_->branchname } @libraries };
442     my @locations = Koha::AuthorisedValues->search( { category => 'LOC' } );
443     my $opac = C4::Context->interface eq 'opac' ;
444     my %special = (
445         itype    => { map { $_->itemtype         => $_->description } @itypes },
446         location => { map { $_->authorised_value => ( $opac ? ( $_->lib_opac || $_->lib ) : $_->lib ) } @locations },
447         holdingbranch => $library_names,
448         homebranch => $library_names
449     );
450     my @facets;
451     $exp_facet //= '';
452     while ( my ( $type, $data ) = each %$es ) {
453         next if !exists( $type_to_label{$type} );
454
455         # We restrict to the most popular $limit !results
456         my $limit = ( $type eq $exp_facet ) ? C4::Context->preference('FacetMaxCount') : 5;
457         my $facet = {
458             type_id    => $type . '_id',
459             expand     => $type,
460             expandable => ( $type ne $exp_facet )
461               && ( @{ $data->{buckets} } > $limit ),
462             "type_label_$type_to_label{$type}{label}" => 1,
463             type_link_value                    => $type,
464             order      => $type_to_label{$type}{order},
465         };
466         $limit = @{ $data->{buckets} } if ( $limit > @{ $data->{buckets} } );
467         foreach my $term ( @{ $data->{buckets} }[ 0 .. $limit - 1 ] ) {
468             my $t = $term->{key};
469             my $c = $term->{doc_count};
470             my $label;
471             if ( exists( $special{$type} ) ) {
472                 $label = $special{$type}->{$t} // $t;
473             }
474             else {
475                 $label = $t;
476             }
477             push @{ $facet->{facets} }, {
478                 facet_count       => $c,
479                 facet_link_value  => $t,
480                 facet_title_value => $t . " ($c)",
481                 facet_label_value => $label,        # TODO either truncate this,
482                      # or make the template do it like it should anyway
483                 type_link_value => $type,
484             };
485         }
486         push @facets, $facet if exists $facet->{facets};
487     }
488
489     @facets = sort { $a->{order} cmp $b->{order} } @facets;
490     return \@facets;
491 }
492
493
494 1;