Bug 18290: Fix t/db_dependent/Koha/Object.t, Mojo::JSON::Bool is a JSON::PP::Boolean :)
[koha.git] / Koha / SearchEngine / Elasticsearch.pm
blob43bb0a83a834db7c6da7eeee7de7f8788ab699d9
1 package Koha::SearchEngine::Elasticsearch;
3 # Copyright 2015 Catalyst IT
5 # This file is part of Koha.
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.
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.
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.
20 use base qw(Class::Accessor);
22 use C4::Context;
24 use Koha::Database;
25 use Koha::SearchFields;
26 use Koha::SearchMarcMaps;
28 use Carp;
29 use JSON;
30 use Modern::Perl;
31 use Readonly;
32 use YAML::Syck;
34 use Data::Dumper; # TODO remove
36 __PACKAGE__->mk_ro_accessors(qw( index ));
37 __PACKAGE__->mk_accessors(qw( sort_fields ));
39 # Constants to refer to the standard index names
40 Readonly our $BIBLIOS_INDEX => 'biblios';
41 Readonly our $AUTHORITIES_INDEX => 'authorities';
43 =head1 NAME
45 Koha::SearchEngine::Elasticsearch - Base module for things using elasticsearch
47 =head1 ACCESSORS
49 =over 4
51 =item index
53 The name of the index to use, generally 'biblios' or 'authorities'.
55 =back
57 =head1 FUNCTIONS
59 =cut
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;
69 =head2 get_elasticsearch_params
71 my $params = $self->get_elasticsearch_params();
73 This provides a hashref that contains the parameters for connecting to the
74 ElasicSearch servers, in the form:
77 'nodes' => ['127.0.0.1:9200', 'anotherserver:9200'],
78 'index_name' => 'koha_instance_index',
81 This is configured by the following in the C<config> block in koha-conf.xml:
83 <elasticsearch>
84 <server>127.0.0.1:9200</server>
85 <server>anotherserver:9200</server>
86 <index_name>koha_instance</index_name>
87 </elasticsearch>
89 =cut
91 sub get_elasticsearch_params {
92 my ($self) = @_;
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 } };
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' ) {
105 # store it called 'nodes' (which is used by newer Search::Elasticsearch)
106 $es->{nodes} = $server;
108 elsif ($server) {
109 $es->{nodes} = [$server];
111 else {
112 die "No elasticsearch servers were specified in koha-conf.xml.\n";
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;
119 $es->{key_prefix} = 'es_';
120 return $es;
123 =head2 get_elasticsearch_settings
125 my $settings = $self->get_elasticsearch_settings();
127 This provides the settings provided to elasticsearch when an index is created.
128 These can do things like define tokenisation methods.
130 A hashref containing the settings is returned.
132 =cut
134 sub get_elasticsearch_settings {
135 my ($self) = @_;
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 => 'keyword',
145 filter => ['lowercase'],
147 analyser_standard => {
148 tokenizer => 'standard',
149 filter => ['lowercase'],
155 return $settings;
158 =head2 get_elasticsearch_mappings
160 my $mappings = $self->get_elasticsearch_mappings();
162 This provides the mappings that get passed to elasticsearch when an index is
163 created.
165 =cut
167 sub get_elasticsearch_mappings {
168 my ($self) = @_;
170 # TODO cache in the object?
171 my $mappings = {
172 data => {
173 properties => {
174 record => {
175 store => "true",
176 include_in_all => JSON::false,
177 type => "text",
182 my %sort_fields;
183 my $marcflavour = lc C4::Context->preference('marcflavour');
184 $self->_foreach_mapping(
185 sub {
186 my ( $name, $type, $facet, $suggestible, $sort, $marc_type ) = @_;
187 return if $marc_type ne $marcflavour;
188 # TODO if this gets any sort of complexity to it, it should
189 # be broken out into its own function.
191 # TODO be aware of date formats, but this requires pre-parsing
192 # as ES will simply reject anything with an invalid date.
193 my $es_type =
194 $type eq 'boolean'
195 ? 'boolean'
196 : 'text';
198 if ($es_type eq 'boolean') {
199 $mappings->{data}{properties}{$name} = _elasticsearch_mapping_for_boolean( $name, $es_type, $facet, $suggestible, $sort, $marc_type );
200 return; #Boolean cannot have facets nor sorting nor suggestions
201 } else {
202 $mappings->{data}{properties}{$name} = _elasticsearch_mapping_for_default( $name, $es_type, $facet, $suggestible, $sort, $marc_type );
205 if ($facet) {
206 $mappings->{data}{properties}{ $name . '__facet' } = {
207 type => "keyword",
210 if ($suggestible) {
211 $mappings->{data}{properties}{ $name . '__suggestion' } = {
212 type => 'completion',
213 analyzer => 'simple',
214 search_analyzer => 'simple',
217 # Sort may be true, false, or undef. Here we care if it's
218 # anything other than undef.
219 if (defined $sort) {
220 $mappings->{data}{properties}{ $name . '__sort' } = {
221 search_analyzer => "analyser_phrase",
222 analyzer => "analyser_phrase",
223 type => "text",
224 include_in_all => JSON::false,
225 fields => {
226 phrase => {
227 type => "keyword",
231 $sort_fields{$name} = 1;
235 $self->sort_fields(\%sort_fields);
236 return $mappings;
239 =head2 _elasticsearch_mapping_for_*
241 Get the ES mappings for the given data type or a special mapping case
243 Receives the same parameters from the $self->_foreach_mapping() dispatcher
245 =cut
247 sub _elasticsearch_mapping_for_boolean {
248 my ( $name, $type, $facet, $suggestible, $sort, $marc_type ) = @_;
250 return {
251 type => $type,
252 null_value => 0,
256 sub _elasticsearch_mapping_for_default {
257 my ( $name, $type, $facet, $suggestible, $sort, $marc_type ) = @_;
259 return {
260 search_analyzer => "analyser_standard",
261 analyzer => "analyser_standard",
262 type => $type,
263 fields => {
264 phrase => {
265 search_analyzer => "analyser_phrase",
266 analyzer => "analyser_phrase",
267 type => "text",
269 raw => {
270 type => "keyword",
276 sub reset_elasticsearch_mappings {
277 my $mappings_yaml = C4::Context->config('intranetdir') . '/admin/searchengine/elasticsearch/mappings.yaml';
278 my $indexes = LoadFile( $mappings_yaml );
280 while ( my ( $index_name, $fields ) = each %$indexes ) {
281 while ( my ( $field_name, $data ) = each %$fields ) {
282 my $field_type = $data->{type};
283 my $field_label = $data->{label};
284 my $mappings = $data->{mappings};
285 my $search_field = Koha::SearchFields->find_or_create({ name => $field_name, label => $field_label, type => $field_type }, { key => 'name' });
286 for my $mapping ( @$mappings ) {
287 my $marc_field = Koha::SearchMarcMaps->find_or_create({ index_name => $index_name, marc_type => $mapping->{marc_type}, marc_field => $mapping->{marc_field} });
288 $search_field->add_to_search_marc_maps($marc_field, { facet => $mapping->{facet} || 0, suggestible => $mapping->{suggestible} || 0, sort => $mapping->{sort} } );
294 # This overrides the accessor provided by Class::Accessor so that if
295 # sort_fields isn't set, then it'll generate it.
296 sub sort_fields {
297 my $self = shift;
299 if (@_) {
300 $self->_sort_fields_accessor(@_);
301 return;
303 my $val = $self->_sort_fields_accessor();
304 return $val if $val;
306 # This will populate the accessor as a side effect
307 $self->get_elasticsearch_mappings();
308 return $self->_sort_fields_accessor();
311 # Provides the rules for data conversion.
312 sub get_fixer_rules {
313 my ($self) = @_;
315 my $marcflavour = lc C4::Context->preference('marcflavour');
316 my @rules;
318 $self->_foreach_mapping(
319 sub {
320 my ( $name, $type, $facet, $suggestible, $sort, $marc_type, $marc_field ) = @_;
321 return if $marc_type ne $marcflavour;
322 my $options = '';
324 # There's a bug when using 'split' with something that
325 # selects a range
326 # The split makes everything into nested arrays, but that's not
327 # really a big deal, ES doesn't mind.
328 $options = '-split => 1' unless $marc_field =~ m|_/| || $type eq 'sum';
329 push @rules, "marc_map('$marc_field','${name}.\$append', $options)";
330 if ($facet) {
331 push @rules, "marc_map('$marc_field','${name}__facet.\$append', $options)";
333 if ($suggestible) {
334 push @rules,
335 #"marc_map('$marc_field','${name}__suggestion.input.\$append', $options)"; #must not have nested data structures in .input
336 "marc_map('$marc_field','${name}__suggestion.input.\$append')";
338 if ( $type eq 'boolean' ) {
340 # boolean gets special handling, basically if it doesn't exist,
341 # it's added and set to false. Otherwise we can't query it.
342 push @rules,
343 "unless exists('$name') add_field('$name', 0) end";
345 if ($type eq 'sum' ) {
346 push @rules, "sum('$name')";
348 # Sort is a bit special as it can be true, false, undef. For
349 # fixer rules, we care about "true", or "undef" if there is
350 # special handling of this field from other one. "undef" means
351 # to do the default thing, which is make it sortable.
352 if ($self->sort_fields()->{$name}) {
353 if ($sort || !defined $sort) {
354 push @rules, "marc_map('$marc_field','${name}__sort.\$append', $options)";
360 push @rules, "move_field(_id,es_id)"; #Also you must set the Catmandu::Store::ElasticSearch->new(key_prefix: 'es_');
361 return \@rules;
364 =head2 _foreach_mapping
366 $self->_foreach_mapping(
367 sub {
368 my ( $name, $type, $facet, $suggestible, $sort, $marc_type,
369 $marc_field )
370 = @_;
371 return unless $marc_type eq 'marc21';
372 print "Data comes from: " . $marc_field . "\n";
376 This allows you to apply a function to each entry in the elasticsearch mappings
377 table, in order to build the mappings for whatever is needed.
379 In the provided function, the files are:
381 =over 4
383 =item C<$name>
385 The field name for elasticsearch (corresponds to the 'mapping' column in the
386 database.
388 =item C<$type>
390 The type for this value, e.g. 'string'.
392 =item C<$facet>
394 True if this value should be facetised. This only really makes sense if the
395 field is understood by the facet processing code anyway.
397 =item C<$sort>
399 True if this is a field that a) needs special sort handling, and b) if it
400 should be sorted on. False if a) but not b). Undef if not a). This allows,
401 for example, author to be sorted on but not everything marked with "author"
402 to be included in that sort.
404 =item C<$marc_type>
406 A string that indicates the MARC type that this mapping is for, e.g. 'marc21',
407 'unimarc', 'normarc'.
409 =item C<$marc_field>
411 A string that describes the MARC field that contains the data to extract.
412 These are of a form suited to Catmandu's MARC fixers.
414 =back
416 =cut
418 sub _foreach_mapping {
419 my ( $self, $sub ) = @_;
421 # TODO use a caching framework here
422 my $search_fields = Koha::Database->schema->resultset('SearchField')->search(
424 'search_marc_map.index_name' => $self->index,
426 { join => { search_marc_to_fields => 'search_marc_map' },
427 '+select' => [
428 'search_marc_to_fields.facet',
429 'search_marc_to_fields.suggestible',
430 'search_marc_to_fields.sort',
431 'search_marc_map.marc_type',
432 'search_marc_map.marc_field',
434 '+as' => [
435 'facet',
436 'suggestible',
437 'sort',
438 'marc_type',
439 'marc_field',
444 while ( my $search_field = $search_fields->next ) {
445 $sub->(
446 $search_field->name,
447 $search_field->type,
448 $search_field->get_column('facet'),
449 $search_field->get_column('suggestible'),
450 $search_field->get_column('sort'),
451 $search_field->get_column('marc_type'),
452 $search_field->get_column('marc_field'),
457 =head2 process_error
459 die process_error($@);
461 This parses an Elasticsearch error message and produces a human-readable
462 result from it. This result is probably missing all the useful information
463 that you might want in diagnosing an issue, so the warning is also logged.
465 Note that currently the resulting message is not internationalised. This
466 will happen eventually by some method or other.
468 =cut
470 sub process_error {
471 my ($self, $msg) = @_;
473 warn $msg; # simple logging
475 # This is super-primitive
476 return "Unable to understand your search query, please rephrase and try again.\n" if $msg =~ /ParseException/;
478 return "Unable to perform your search. Please try again.\n";
483 __END__
485 =head1 AUTHOR
487 =over 4
489 =item Chris Cormack C<< <chrisc@catalyst.net.nz> >>
491 =item Robin Sheat C<< <robin@catalyst.net.nz> >>
493 =item Jonathan Druart C<< <jonathan.druart@bugs.koha-community.org> >>
495 =back
497 =cut