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