Bug 19563: (follow-up) Restore checking sort variable
[koha.git] / Koha / SearchEngine / Elasticsearch.pm
1 package Koha::SearchEngine::Elasticsearch;
2
3 # Copyright 2015 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 use base qw(Class::Accessor);
21
22 use C4::Context;
23
24 use Koha::Database;
25 use Koha::SearchFields;
26 use Koha::SearchMarcMaps;
27
28 use Carp;
29 use JSON;
30 use Modern::Perl;
31 use Readonly;
32 use YAML::Syck;
33
34 use Data::Dumper;    # TODO remove
35
36 __PACKAGE__->mk_ro_accessors(qw( index ));
37 __PACKAGE__->mk_accessors(qw( sort_fields ));
38
39 # Constants to refer to the standard index names
40 Readonly our $BIBLIOS_INDEX     => 'biblios';
41 Readonly our $AUTHORITIES_INDEX => 'authorities';
42
43 =head1 NAME
44
45 Koha::SearchEngine::Elasticsearch - Base module for things using elasticsearch
46
47 =head1 ACCESSORS
48
49 =over 4
50
51 =item index
52
53 The name of the index to use, generally 'biblios' or 'authorities'.
54
55 =back
56
57 =head1 FUNCTIONS
58
59 =cut
60
61 sub new {
62     my $class = shift @_;
63     my $self = $class->SUPER::new(@_);
64     # Check for a valid index
65     croak('No index name provided') unless $self->index;
66     return $self;
67 }
68
69 =head2 get_elasticsearch_params
70
71     my $params = $self->get_elasticsearch_params();
72
73 This provides a hashref that contains the parameters for connecting to the
74 ElasicSearch servers, in the form:
75
76     {
77         'nodes' => ['127.0.0.1:9200', 'anotherserver:9200'],
78         'index_name' => 'koha_instance_index',
79     }
80
81 This is configured by the following in the C<config> block in koha-conf.xml:
82
83     <elasticsearch>
84         <server>127.0.0.1:9200</server>
85         <server>anotherserver:9200</server>
86         <index_name>koha_instance</index_name>
87     </elasticsearch>
88
89 =cut
90
91 sub get_elasticsearch_params {
92     my ($self) = @_;
93
94     # Copy the hash so that we're not modifying the original
95     my $conf = C4::Context->config('elasticsearch');
96     die "No 'elasticsearch' block is defined in koha-conf.xml.\n" if ( !$conf );
97     my $es = { %{ $conf } };
98
99     # Helpfully, the multiple server lines end up in an array for us anyway
100     # if there are multiple ones, but not if there's only one.
101     my $server = $es->{server};
102     delete $es->{server};
103     if ( ref($server) eq 'ARRAY' ) {
104
105         # store it called 'nodes' (which is used by newer Search::Elasticsearch)
106         $es->{nodes} = $server;
107     }
108     elsif ($server) {
109         $es->{nodes} = [$server];
110     }
111     else {
112         die "No elasticsearch servers were specified in koha-conf.xml.\n";
113     }
114     die "No elasticserver index_name was specified in koha-conf.xml.\n"
115       if ( !$es->{index_name} );
116     # Append the name of this particular index to our namespace
117     $es->{index_name} .= '_' . $self->index;
118
119     $es->{key_prefix} = 'es_';
120     return $es;
121 }
122
123 =head2 get_elasticsearch_settings
124
125     my $settings = $self->get_elasticsearch_settings();
126
127 This provides the settings provided to elasticsearch when an index is created.
128 These can do things like define tokenisation methods.
129
130 A hashref containing the settings is returned.
131
132 =cut
133
134 sub get_elasticsearch_settings {
135     my ($self) = @_;
136
137     # Ultimately this should come from a file or something, and not be
138     # hardcoded.
139     my $settings = {
140         index => {
141             analysis => {
142                 analyzer => {
143                     analyser_phrase => {
144                         tokenizer => 'icu_tokenizer',
145                         filter    => ['icu_folding'],
146                     },
147                     analyser_standard => {
148                         tokenizer => 'icu_tokenizer',
149                         filter    => ['icu_folding'],
150                     },
151                 },
152             }
153         }
154     };
155     return $settings;
156 }
157
158 =head2 get_elasticsearch_mappings
159
160     my $mappings = $self->get_elasticsearch_mappings();
161
162 This provides the mappings that get passed to elasticsearch when an index is
163 created.
164
165 =cut
166
167 sub get_elasticsearch_mappings {
168     my ($self) = @_;
169
170     # TODO cache in the object?
171     my $mappings = {
172         data => {
173             _all => {type => "string", analyzer => "analyser_standard"},
174             properties => {
175                 record => {
176                     store          => "true",
177                     include_in_all => JSON::false,
178                     type           => "text",
179                 },
180             }
181         }
182     };
183     my %sort_fields;
184     my $marcflavour = lc C4::Context->preference('marcflavour');
185     $self->_foreach_mapping(
186         sub {
187             my ( $name, $type, $facet, $suggestible, $sort, $marc_type ) = @_;
188             return if $marc_type ne $marcflavour;
189             # TODO if this gets any sort of complexity to it, it should
190             # be broken out into its own function.
191
192             # TODO be aware of date formats, but this requires pre-parsing
193             # as ES will simply reject anything with an invalid date.
194             my $es_type =
195               $type eq 'boolean'
196               ? 'boolean'
197               : 'text';
198
199             if ($es_type eq 'boolean') {
200                 $mappings->{data}{properties}{$name} = _elasticsearch_mapping_for_boolean( $name, $es_type, $facet, $suggestible, $sort, $marc_type );
201                 return; #Boolean cannot have facets nor sorting nor suggestions
202             } else {
203                 $mappings->{data}{properties}{$name} = _elasticsearch_mapping_for_default( $name, $es_type, $facet, $suggestible, $sort, $marc_type );
204             }
205
206             if ($facet) {
207                 $mappings->{data}{properties}{ $name . '__facet' } = {
208                     type  => "keyword",
209                 };
210             }
211             if ($suggestible) {
212                 $mappings->{data}{properties}{ $name . '__suggestion' } = {
213                     type => 'completion',
214                     analyzer => 'simple',
215                     search_analyzer => 'simple',
216                 };
217             }
218             # Sort is a bit special as it can be true, false, undef.
219             # We care about "true" or "undef",
220             # "undef" means to do the default thing, which is make it sortable.
221             if ($sort || !defined $sort) {
222                 $mappings->{data}{properties}{ $name . '__sort' } = {
223                     search_analyzer => "analyser_phrase",
224                     analyzer  => "analyser_phrase",
225                     type            => "text",
226                     include_in_all  => JSON::false,
227                     fields          => {
228                         phrase => {
229                             type            => "keyword",
230                         },
231                     },
232                 };
233                 $sort_fields{$name} = 1;
234             }
235         }
236     );
237     $self->sort_fields(\%sort_fields);
238     return $mappings;
239 }
240
241 =head2 _elasticsearch_mapping_for_*
242
243 Get the ES mappings for the given data type or a special mapping case
244
245 Receives the same parameters from the $self->_foreach_mapping() dispatcher
246
247 =cut
248
249 sub _elasticsearch_mapping_for_boolean {
250     my ( $name, $type, $facet, $suggestible, $sort, $marc_type ) = @_;
251
252     return {
253         type            => $type,
254         null_value      => 0,
255     };
256 }
257
258 sub _elasticsearch_mapping_for_default {
259     my ( $name, $type, $facet, $suggestible, $sort, $marc_type ) = @_;
260
261     return {
262         search_analyzer => "analyser_standard",
263         analyzer        => "analyser_standard",
264         type            => $type,
265         fields          => {
266             phrase => {
267                 search_analyzer => "analyser_phrase",
268                 analyzer        => "analyser_phrase",
269                 type            => "text",
270             },
271             raw => {
272                 type    => "keyword",
273             }
274         },
275     };
276 }
277
278 sub reset_elasticsearch_mappings {
279     my $mappings_yaml = C4::Context->config('intranetdir') . '/admin/searchengine/elasticsearch/mappings.yaml';
280     my $indexes = LoadFile( $mappings_yaml );
281
282     while ( my ( $index_name, $fields ) = each %$indexes ) {
283         while ( my ( $field_name, $data ) = each %$fields ) {
284             my $field_type = $data->{type};
285             my $field_label = $data->{label};
286             my $mappings = $data->{mappings};
287             my $search_field = Koha::SearchFields->find_or_create({ name => $field_name, label => $field_label, type => $field_type }, { key => 'name' });
288             for my $mapping ( @$mappings ) {
289                 my $marc_field = Koha::SearchMarcMaps->find_or_create({ index_name => $index_name, marc_type => $mapping->{marc_type}, marc_field => $mapping->{marc_field} });
290                 $search_field->add_to_search_marc_maps($marc_field, { facet => $mapping->{facet} || 0, suggestible => $mapping->{suggestible} || 0, sort => $mapping->{sort} } );
291             }
292         }
293     }
294 }
295
296 # This overrides the accessor provided by Class::Accessor so that if
297 # sort_fields isn't set, then it'll generate it.
298 sub sort_fields {
299     my $self = shift;
300     if (@_) {
301         $self->_sort_fields_accessor(@_);
302         return;
303     }
304     my $val = $self->_sort_fields_accessor();
305     return $val if $val;
306
307     # This will populate the accessor as a side effect
308     $self->get_elasticsearch_mappings();
309     return $self->_sort_fields_accessor();
310 }
311
312 # Provides the rules for data conversion.
313 sub get_fixer_rules {
314     my ($self) = @_;
315
316     my $marcflavour = lc C4::Context->preference('marcflavour');
317     my @rules;
318
319     $self->_foreach_mapping(
320         sub {
321             my ( $name, $type, $facet, $suggestible, $sort, $marc_type, $marc_field ) = @_;
322             return if $marc_type ne $marcflavour;
323             my $options = '';
324
325             # There's a bug when using 'split' with something that
326             # selects a range
327             # The split makes everything into nested arrays, but that's not
328             # really a big deal, ES doesn't mind.
329             $options = '-split => 1' unless $marc_field =~ m|_/| || $type eq 'sum';
330             push @rules, "marc_map('$marc_field','${name}.\$append', $options)";
331             if ($facet) {
332                 push @rules, "marc_map('$marc_field','${name}__facet.\$append', $options)";
333             }
334             if ($suggestible) {
335                 push @rules,
336                     #"marc_map('$marc_field','${name}__suggestion.input.\$append', $options)"; #must not have nested data structures in .input
337                     "marc_map('$marc_field','${name}__suggestion.input.\$append')";
338             }
339             if ( $type eq 'boolean' ) {
340
341                 # boolean gets special handling, basically if it doesn't exist,
342                 # it's added and set to false. Otherwise we can't query it.
343                 push @rules,
344                   "unless exists('$name') add_field('$name', 0) end";
345             }
346             if ($type eq 'sum' ) {
347                 push @rules, "sum('$name')";
348             }
349             if ($self->sort_fields()->{$name}) {
350                 if ($sort || !defined $sort) {
351                     push @rules, "marc_map('$marc_field','${name}__sort.\$append', $options)";
352                 }
353             }
354         }
355     );
356
357     push @rules, "move_field(_id,es_id)"; #Also you must set the Catmandu::Store::ElasticSearch->new(key_prefix: 'es_');
358     return \@rules;
359 }
360
361 =head2 _foreach_mapping
362
363     $self->_foreach_mapping(
364         sub {
365             my ( $name, $type, $facet, $suggestible, $sort, $marc_type,
366                 $marc_field )
367               = @_;
368             return unless $marc_type eq 'marc21';
369             print "Data comes from: " . $marc_field . "\n";
370         }
371     );
372
373 This allows you to apply a function to each entry in the elasticsearch mappings
374 table, in order to build the mappings for whatever is needed.
375
376 In the provided function, the files are:
377
378 =over 4
379
380 =item C<$name>
381
382 The field name for elasticsearch (corresponds to the 'mapping' column in the
383 database.
384
385 =item C<$type>
386
387 The type for this value, e.g. 'string'.
388
389 =item C<$facet>
390
391 True if this value should be facetised. This only really makes sense if the
392 field is understood by the facet processing code anyway.
393
394 =item C<$sort>
395
396 True if this is a field that a) needs special sort handling, and b) if it
397 should be sorted on. False if a) but not b). Undef if not a). This allows,
398 for example, author to be sorted on but not everything marked with "author"
399 to be included in that sort.
400
401 =item C<$marc_type>
402
403 A string that indicates the MARC type that this mapping is for, e.g. 'marc21',
404 'unimarc', 'normarc'.
405
406 =item C<$marc_field>
407
408 A string that describes the MARC field that contains the data to extract.
409 These are of a form suited to Catmandu's MARC fixers.
410
411 =back
412
413 =cut
414
415 sub _foreach_mapping {
416     my ( $self, $sub ) = @_;
417
418     # TODO use a caching framework here
419     my $search_fields = Koha::Database->schema->resultset('SearchField')->search(
420         {
421             'search_marc_map.index_name' => $self->index,
422         },
423         {   join => { search_marc_to_fields => 'search_marc_map' },
424             '+select' => [
425                 'search_marc_to_fields.facet',
426                 'search_marc_to_fields.suggestible',
427                 'search_marc_to_fields.sort',
428                 'search_marc_map.marc_type',
429                 'search_marc_map.marc_field',
430             ],
431             '+as'     => [
432                 'facet',
433                 'suggestible',
434                 'sort',
435                 'marc_type',
436                 'marc_field',
437             ],
438         }
439     );
440
441     while ( my $search_field = $search_fields->next ) {
442         $sub->(
443             $search_field->name,
444             $search_field->type,
445             $search_field->get_column('facet'),
446             $search_field->get_column('suggestible'),
447             $search_field->get_column('sort'),
448             $search_field->get_column('marc_type'),
449             $search_field->get_column('marc_field'),
450         );
451     }
452 }
453
454 =head2 process_error
455
456     die process_error($@);
457
458 This parses an Elasticsearch error message and produces a human-readable
459 result from it. This result is probably missing all the useful information
460 that you might want in diagnosing an issue, so the warning is also logged.
461
462 Note that currently the resulting message is not internationalised. This
463 will happen eventually by some method or other.
464
465 =cut
466
467 sub process_error {
468     my ($self, $msg) = @_;
469
470     warn $msg; # simple logging
471
472     # This is super-primitive
473     return "Unable to understand your search query, please rephrase and try again.\n" if $msg =~ /ParseException/;
474
475     return "Unable to perform your search. Please try again.\n";
476 }
477
478 1;
479
480 __END__
481
482 =head1 AUTHOR
483
484 =over 4
485
486 =item Chris Cormack C<< <chrisc@catalyst.net.nz> >>
487
488 =item Robin Sheat C<< <robin@catalyst.net.nz> >>
489
490 =item Jonathan Druart C<< <jonathan.druart@bugs.koha-community.org> >>
491
492 =back
493
494 =cut