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