Bug 18213: (follow-up) Correctly sort facets
[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 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,       $expanded_facet, $branches,
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,       $expanded_facet,
149         $branches, $query_type,       $scan
150     ) = @_;
151     my %options;
152     if ( !defined $offset or $offset < 0 ) {
153         $offset = 0;
154     }
155     $options{offset} = $offset;
156     $options{expanded_facet} = $expanded_facet;
157     my $results = $self->search($query, undef, $results_per_page, %options);
158
159     # Convert each result into a MARC::Record
160     my @records;
161     # opac-search expects results to be put in the
162     # right place in the array, according to $offset
163     my $index = $offset;
164     my $hits = $results->{'hits'};
165     foreach my $es_record (@{$hits->{'hits'}}) {
166         $records[$index++] = $self->decode_record_from_result($es_record->{'_source'});
167     }
168
169     # consumers of this expect a name-spaced result, we provide the default
170     # configuration.
171     my %result;
172     $result{biblioserver}{hits} = $hits->{'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, $offset, $count, $skipmetadata, %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, $query, $offset, $count, $skipmetadata, %options) = @_;
189
190     if ( !defined $offset or $offset <= 0 ) {
191         $offset = 1;
192     }
193     # Uh, authority search uses 1-based offset..
194     $options{offset} = $offset - 1;
195     my $database = Koha::Database->new();
196     my $schema   = $database->schema();
197     my $res      = $self->search($query, undef, $count, %options);
198
199     my $bib_searcher = Koha::SearchEngine::Elasticsearch::Search->new({index => 'biblios'});
200     my @records;
201     my $hits = $res->{'hits'};
202     foreach my $es_record (@{$hits->{'hits'}}) {
203         my $record = $es_record->{'_source'};
204         my %result;
205
206         # I wonder if these should be real values defined in the mapping
207         # rather than hard-coded conversions.
208         #my $record    = $_[0];
209         # Handle legacy nested arrays indexed with splitting enabled.
210         my $authid = $record->{ 'local-number' }[0];
211         $authid = @$authid[0] if (ref $authid eq 'ARRAY');
212
213         $result{authid} = $authid;
214
215         if (!defined $skipmetadata || !$skipmetadata) {
216             # TODO put all this info into the record at index time so we
217             # don't have to go and sort it all out now.
218             my $authtypecode = $record->{authtype};
219             my $rs           = $schema->resultset('AuthType')
220             ->search( { authtypecode => $authtypecode } );
221
222             # FIXME there's an assumption here that we will get a result.
223             # the original code also makes an assumption that some provided
224             # authtypecode may sometimes be used instead of the one stored
225             # with the record. It's not documented why this is the case, so
226             # it's not reproduced here yet.
227             my $authtype           = $rs->single;
228             my $auth_tag_to_report = $authtype ? $authtype->auth_tag_to_report : "";
229             my $marc               = $self->decode_record_from_result($record);
230             my $mainentry          = $marc->field($auth_tag_to_report);
231             my $reported_tag;
232             if ($mainentry) {
233                 foreach ( $mainentry->subfields() ) {
234                     $reported_tag .= '$' . $_->[0] . $_->[1];
235                 }
236             }
237             # Turn the resultset into a hash
238             $result{authtype}     = $authtype ? $authtype->authtypetext : $authtypecode;
239             $result{reported_tag} = $reported_tag;
240
241             # Reimplementing BuildSummary is out of scope because it'll be hard
242             $result{summary} =
243             C4::AuthoritiesMarc::BuildSummary( $marc, $result{authid},
244                 $authtypecode );
245             $result{used} = $self->count_auth_use($bib_searcher, $authid);
246         }
247         push @records, \%result;
248     }
249     return ( \@records, $hits->{'total'} );
250 }
251
252 =head2 count_auth_use
253
254     my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
255
256 This runs a search to determine the number of records that reference the
257 specified authid. C<$bib_searcher> must be something compatible with
258 elasticsearch, as the query is built in this function.
259
260 =cut
261
262 sub count_auth_use {
263     my ($self, $bib_searcher, $authid) = @_;
264
265     my $query = {
266         query => {
267             bool => {
268 #                query  => { match_all => {} },
269                 filter => { term      => { 'koha-auth-number' => $authid } }
270             }
271         }
272     };
273     $bib_searcher->count($query);
274 }
275
276 =head2 simple_search_compat
277
278     my ( $error, $marcresults, $total_hits ) =
279       $searcher->simple_search( $query, $offset, $max_results, %options );
280
281 This is a simpler interface to the searching, intended to be similar enough to
282 L<C4::Search::SimpleSearch>.
283
284 Arguments:
285
286 =over 4
287
288 =item C<$query>
289
290 A thing to search for. It could be a simple string, or something constructed
291 with the appropriate QueryBuilder module.
292
293 =item C<$offset>
294
295 How many results to skip from the start of the results.
296
297 =item C<$max_results>
298
299 The max number of results to return. The default is 100 (because unlimited
300 is a pretty terrible thing to do.)
301
302 =item C<%options>
303
304 These options are unused by Elasticsearch
305
306 =back
307
308 Returns:
309
310 =over 4
311
312 =item C<$error>
313
314 if something went wrong, this'll contain some kind of error
315 message.
316
317 =item C<$marcresults>
318
319 an arrayref of MARC::Records (note that this is different from the
320 L<C4::Search> version which will return plain XML, but too bad.)
321
322 =item C<$total_hits>
323
324 the total number of results that this search could have returned.
325
326 =back
327
328 =cut
329
330 sub simple_search_compat {
331     my ($self, $query, $offset, $max_results) = @_;
332
333     return ('No query entered', undef, undef) unless $query;
334
335     my %options;
336     $offset = 0 if not defined $offset or $offset < 0;
337     $options{offset} = $offset;
338     $max_results //= 100;
339
340     unless (ref $query) {
341         # We'll push it through the query builder to sanitise everything.
342         my $qb = Koha::SearchEngine::QueryBuilder->new({index => $self->index});
343         (undef,$query) = $qb->build_query_compat(undef, [$query]);
344     }
345     my $results = $self->search($query, undef, $max_results, %options);
346     my @records;
347     my $hits = $results->{'hits'};
348     foreach my $es_record (@{$hits->{'hits'}}) {
349         push @records, $self->decode_record_from_result($es_record->{'_source'});
350     }
351     return (undef, \@records, $hits->{'total'});
352 }
353
354 =head2 extract_biblionumber
355
356     my $biblionumber = $searcher->extract_biblionumber( $searchresult );
357
358 $searchresult comes from simple_search_compat.
359
360 Returns the biblionumber from the search result record.
361
362 =cut
363
364 sub extract_biblionumber {
365     my ( $self, $searchresultrecord ) = @_;
366     return Koha::SearchEngine::Search::extract_biblionumber( $searchresultrecord );
367 }
368
369 =head2 decode_record_from_result
370     my $marc_record = $self->decode_record_from_result(@result);
371
372 Extracts marc data from Elasticsearch result and decodes to MARC::Record object
373
374 =cut
375
376 sub decode_record_from_result {
377     # Result is passed in as array, will get flattened
378     # and first element will be $result
379     my ( $self, $result ) = @_;
380     if ($result->{marc_format} eq 'base64ISO2709') {
381         return MARC::Record->new_from_usmarc(decode_base64($result->{marc_data}));
382     }
383     elsif ($result->{marc_format} eq 'MARCXML') {
384         return MARC::Record->new_from_xml($result->{marc_data}, 'UTF-8', uc C4::Context->preference('marcflavour'));
385     }
386     else {
387         Koha::Exceptions::Elasticsearch->throw("Missing marc_format field in Elasticsearch result");
388     }
389 }
390
391 =head2 max_result_window
392
393 Returns the maximum number of results that can be fetched
394
395 This directly requests Elasticsearch for the setting index.max_result_window (or
396 the default value for this setting in case it is not set)
397
398 =cut
399
400 sub max_result_window {
401     my ($self) = @_;
402
403     $self->store(
404         Catmandu::Store::ElasticSearch->new(%{ $self->get_elasticsearch_params })
405     ) unless $self->store;
406
407     my $index_name = $self->store->index_name;
408     my $settings = $self->store->es->indices->get_settings(
409         index  => $index_name,
410         params => { include_defaults => 'true', flat_settings => 'true' },
411     );
412
413     my $max_result_window = $settings->{$index_name}->{settings}->{'index.max_result_window'};
414     $max_result_window //= $settings->{$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, $expanded_facet);
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 C<$expanded_facet> is the facet that we want to show FacetMaxCount entries for, rather
428 than just 5 like normal.
429
430 =cut
431
432 sub _convert_facets {
433     my ( $self, $es, $exp_facet ) = @_;
434
435     return if !$es;
436
437     # These should correspond to the ES field names, as opposed to the CCL
438     # things that zebra uses.
439     my %type_to_label;
440     my %label = (
441         author         => 'Authors',
442         itype          => 'ItemTypes',
443         location       => 'Location',
444         'su-geo'       => 'Places',
445         'title-series' => 'Series',
446         subject        => 'Topics',
447         ccode          => 'CollectionCodes',
448         holdingbranch  => 'HoldingLibrary',
449         homebranch     => 'HomeLibrary',
450         ln             => 'Language',
451     );
452     my @facetable_fields =
453       Koha::SearchEngine::Elasticsearch->get_facetable_fields;
454     for my $f (@facetable_fields) {
455         next unless defined $f->facet_order;
456         $type_to_label{ $f->name } =
457           { order => $f->facet_order, label => $label{ $f->name } };
458     }
459
460     # We also have some special cases, e.g. itypes that need to show the
461     # value rather than the code.
462     my @itypes = Koha::ItemTypes->search;
463     my @libraries = Koha::Libraries->search;
464     my $library_names = { map { $_->branchcode => $_->branchname } @libraries };
465     my @locations = Koha::AuthorisedValues->search( { category => 'LOC' } );
466     my $opac = C4::Context->interface eq 'opac' ;
467     my %special = (
468         itype    => { map { $_->itemtype         => $_->description } @itypes },
469         location => { map { $_->authorised_value => ( $opac ? ( $_->lib_opac || $_->lib ) : $_->lib ) } @locations },
470         holdingbranch => $library_names,
471         homebranch => $library_names
472     );
473     my @facets;
474     $exp_facet //= '';
475     while ( my ( $type, $data ) = each %$es ) {
476         next if !exists( $type_to_label{$type} );
477
478         # We restrict to the most popular $limit !results
479         my $limit = ( $type eq $exp_facet ) ? C4::Context->preference('FacetMaxCount') : 5;
480         my $facet = {
481             type_id    => $type . '_id',
482             expand     => $type,
483             expandable => ( $type ne $exp_facet )
484               && ( @{ $data->{buckets} } > $limit ),
485             "type_label_$type_to_label{$type}{label}" => 1,
486             type_link_value                    => $type,
487             order      => $type_to_label{$type}{order},
488         };
489         $limit = @{ $data->{buckets} } if ( $limit > @{ $data->{buckets} } );
490         foreach my $term ( @{ $data->{buckets} }[ 0 .. $limit - 1 ] ) {
491             my $t = $term->{key};
492             my $c = $term->{doc_count};
493             my $label;
494             if ( exists( $special{$type} ) ) {
495                 $label = $special{$type}->{$t} // $t;
496             }
497             else {
498                 $label = $t;
499             }
500             push @{ $facet->{facets} }, {
501                 facet_count       => $c,
502                 facet_link_value  => $t,
503                 facet_title_value => $t . " ($c)",
504                 facet_label_value => $label,        # TODO either truncate this,
505                      # or make the template do it like it should anyway
506                 type_link_value => $type,
507             };
508         }
509         push @facets, $facet if exists $facet->{facets};
510     }
511
512     @facets = sort { $a->{order} <=> $b->{order} } @facets;
513     return \@facets;
514 }
515
516 1;