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