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