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