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