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