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