Bug 20434: Add missing authority types
[koha.git] / Koha / SearchEngine / Elasticsearch.pm
blob16532018ba76657411210defbea36cd3cc6b7f9d
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::Exceptions::Config;
26 use Koha::Exceptions::Elasticsearch;
27 use Koha::SearchFields;
28 use Koha::SearchMarcMaps;
30 use Carp;
31 use Clone qw(clone);
32 use JSON;
33 use Modern::Perl;
34 use Readonly;
35 use Search::Elasticsearch;
36 use Try::Tiny;
37 use YAML::Syck;
39 use List::Util qw( sum0 reduce );
40 use MARC::File::XML;
41 use MIME::Base64;
42 use Encode qw(encode);
43 use Business::ISBN;
45 __PACKAGE__->mk_ro_accessors(qw( index ));
46 __PACKAGE__->mk_accessors(qw( sort_fields ));
48 # Constants to refer to the standard index names
49 Readonly our $BIBLIOS_INDEX => 'biblios';
50 Readonly our $AUTHORITIES_INDEX => 'authorities';
52 =head1 NAME
54 Koha::SearchEngine::Elasticsearch - Base module for things using elasticsearch
56 =head1 ACCESSORS
58 =over 4
60 =item index
62 The name of the index to use, generally 'biblios' or 'authorities'.
64 =back
66 =head1 FUNCTIONS
68 =cut
70 sub new {
71 my $class = shift @_;
72 my $self = $class->SUPER::new(@_);
73 # Check for a valid index
74 Koha::Exceptions::MissingParameter->throw('No index name provided') unless $self->index;
75 return $self;
78 =head2 get_elasticsearch
80 my $elasticsearch_client = $self->get_elasticsearch();
82 Returns a C<Search::Elasticsearch> client. The client is cached on a C<Koha::SearchEngine::ElasticSearch>
83 instance level and will be reused if method is called multiple times.
85 =cut
87 sub get_elasticsearch {
88 my $self = shift @_;
89 unless (defined $self->{elasticsearch}) {
90 my $conf = $self->get_elasticsearch_params();
91 $self->{elasticsearch} = Search::Elasticsearch->new($conf);
93 return $self->{elasticsearch};
96 =head2 get_elasticsearch_params
98 my $params = $self->get_elasticsearch_params();
100 This provides a hashref that contains the parameters for connecting to the
101 ElasicSearch servers, in the form:
104 'nodes' => ['127.0.0.1:9200', 'anotherserver:9200'],
105 'index_name' => 'koha_instance_index',
108 This is configured by the following in the C<config> block in koha-conf.xml:
110 <elasticsearch>
111 <server>127.0.0.1:9200</server>
112 <server>anotherserver:9200</server>
113 <index_name>koha_instance</index_name>
114 </elasticsearch>
116 =cut
118 sub get_elasticsearch_params {
119 my ($self) = @_;
121 # Copy the hash so that we're not modifying the original
122 my $conf = C4::Context->config('elasticsearch');
123 die "No 'elasticsearch' block is defined in koha-conf.xml.\n" if ( !$conf );
124 my $es = { %{ $conf } };
126 # Helpfully, the multiple server lines end up in an array for us anyway
127 # if there are multiple ones, but not if there's only one.
128 my $server = $es->{server};
129 delete $es->{server};
130 if ( ref($server) eq 'ARRAY' ) {
132 # store it called 'nodes' (which is used by newer Search::Elasticsearch)
133 $es->{nodes} = $server;
135 elsif ($server) {
136 $es->{nodes} = [$server];
138 else {
139 die "No elasticsearch servers were specified in koha-conf.xml.\n";
141 die "No elasticsearch index_name was specified in koha-conf.xml.\n"
142 if ( !$es->{index_name} );
143 # Append the name of this particular index to our namespace
144 $es->{index_name} .= '_' . $self->index;
146 $es->{key_prefix} = 'es_';
147 $es->{client} //= '5_0::Direct';
148 $es->{cxn_pool} //= 'Static';
149 $es->{request_timeout} //= 60;
151 return $es;
154 =head2 get_elasticsearch_settings
156 my $settings = $self->get_elasticsearch_settings();
158 This provides the settings provided to Elasticsearch when an index is created.
159 These can do things like define tokenization methods.
161 A hashref containing the settings is returned.
163 =cut
165 sub get_elasticsearch_settings {
166 my ($self) = @_;
168 # Use state to speed up repeated calls
169 state $settings = undef;
170 if (!defined $settings) {
171 my $config_file = C4::Context->config('elasticsearch_index_config');
172 $config_file ||= C4::Context->config('intranetdir') . '/admin/searchengine/elasticsearch/index_config.yaml';
173 $settings = LoadFile( $config_file );
176 return $settings;
179 =head2 get_elasticsearch_mappings
181 my $mappings = $self->get_elasticsearch_mappings();
183 This provides the mappings that get passed to Elasticsearch when an index is
184 created.
186 =cut
188 sub get_elasticsearch_mappings {
189 my ($self) = @_;
191 # Use state to speed up repeated calls
192 state %all_mappings;
193 state %sort_fields;
195 if (!defined $all_mappings{$self->index}) {
196 $sort_fields{$self->index} = {};
197 # Clone the general mapping to break ties with the original hash
198 my $mappings = {
199 data => clone(_get_elasticsearch_field_config('general', ''))
201 my $marcflavour = lc C4::Context->preference('marcflavour');
202 $self->_foreach_mapping(
203 sub {
204 my ( $name, $type, $facet, $suggestible, $sort, $search, $marc_type ) = @_;
205 return if $marc_type ne $marcflavour;
206 # TODO if this gets any sort of complexity to it, it should
207 # be broken out into its own function.
209 # TODO be aware of date formats, but this requires pre-parsing
210 # as ES will simply reject anything with an invalid date.
211 my $es_type = 'text';
212 if ($type eq 'boolean') {
213 $es_type = 'boolean';
214 } elsif ($type eq 'number' || $type eq 'sum') {
215 $es_type = 'integer';
216 } elsif ($type eq 'isbn' || $type eq 'stdno') {
217 $es_type = 'stdno';
220 if ($search) {
221 $mappings->{data}{properties}{$name} = _get_elasticsearch_field_config('search', $es_type);
224 if ($facet) {
225 $mappings->{data}{properties}{ $name . '__facet' } = _get_elasticsearch_field_config('facet', $es_type);
227 if ($suggestible) {
228 $mappings->{data}{properties}{ $name . '__suggestion' } = _get_elasticsearch_field_config('suggestible', $es_type);
230 # Sort is a bit special as it can be true, false, undef.
231 # We care about "true" or "undef",
232 # "undef" means to do the default thing, which is make it sortable.
233 if (!defined $sort || $sort) {
234 $mappings->{data}{properties}{ $name . '__sort' } = _get_elasticsearch_field_config('sort', $es_type);
235 $sort_fields{$self->index}{$name} = 1;
239 $all_mappings{$self->index} = $mappings;
241 $self->sort_fields(\%{$sort_fields{$self->index}});
243 return $all_mappings{$self->index};
246 =head2 _get_elasticsearch_field_config
248 Get the Elasticsearch field config for the given purpose and data type.
250 $mapping = _get_elasticsearch_field_config('search', 'text');
252 =cut
254 sub _get_elasticsearch_field_config {
256 my ( $purpose, $type ) = @_;
258 # Use state to speed up repeated calls
259 state $settings = undef;
260 if (!defined $settings) {
261 my $config_file = C4::Context->config('elasticsearch_field_config');
262 $config_file ||= C4::Context->config('intranetdir') . '/admin/searchengine/elasticsearch/field_config.yaml';
263 $settings = LoadFile( $config_file );
266 if (!defined $settings->{$purpose}) {
267 die "Field purpose $purpose not defined in field config";
269 if ($type eq '') {
270 return $settings->{$purpose};
272 if (defined $settings->{$purpose}{$type}) {
273 return $settings->{$purpose}{$type};
275 if (defined $settings->{$purpose}{'default'}) {
276 return $settings->{$purpose}{'default'};
278 return;
281 =head2 _load_elasticsearch_mappings
283 Load Elasticsearch mappings in the format of mappings.yaml.
285 $indexes = _load_elasticsearch_mappings();
287 =cut
289 sub _load_elasticsearch_mappings {
290 my $mappings_yaml = C4::Context->config('elasticsearch_index_mappings');
291 $mappings_yaml ||= C4::Context->config('intranetdir') . '/admin/searchengine/elasticsearch/mappings.yaml';
292 return LoadFile( $mappings_yaml );
295 sub reset_elasticsearch_mappings {
296 my ( $self ) = @_;
297 my $indexes = $self->_load_elasticsearch_mappings();
299 while ( my ( $index_name, $fields ) = each %$indexes ) {
300 while ( my ( $field_name, $data ) = each %$fields ) {
302 my %sf_params = map { $_ => $data->{$_} } grep { exists $data->{$_} } qw/ type label weight staff_client opac facet_order /;
304 # Set default values
305 $sf_params{staff_client} //= 1;
306 $sf_params{opac} //= 1;
308 $sf_params{name} = $field_name;
310 my $search_field = Koha::SearchFields->find_or_create( \%sf_params, { key => 'name' } );
312 my $mappings = $data->{mappings};
313 for my $mapping ( @$mappings ) {
314 my $marc_field = Koha::SearchMarcMaps->find_or_create({
315 index_name => $index_name,
316 marc_type => $mapping->{marc_type},
317 marc_field => $mapping->{marc_field}
319 $search_field->add_to_search_marc_maps($marc_field, {
320 facet => $mapping->{facet} || 0,
321 suggestible => $mapping->{suggestible} || 0,
322 sort => $mapping->{sort},
323 search => $mapping->{search} // 1
330 # This overrides the accessor provided by Class::Accessor so that if
331 # sort_fields isn't set, then it'll generate it.
332 sub sort_fields {
333 my $self = shift;
334 if (@_) {
335 $self->_sort_fields_accessor(@_);
336 return;
338 my $val = $self->_sort_fields_accessor();
339 return $val if $val;
341 # This will populate the accessor as a side effect
342 $self->get_elasticsearch_mappings();
343 return $self->_sort_fields_accessor();
346 =head2 _process_mappings($mappings, $data, $record_document, $altscript)
348 $self->_process_mappings($mappings, $marc_field_data, $record_document, 0)
350 Process all C<$mappings> targets operating on a specific MARC field C<$data>.
351 Since we group all mappings by MARC field targets C<$mappings> will contain
352 all targets for C<$data> and thus we need to fetch the MARC field only once.
353 C<$mappings> will be applied to C<$record_document> and new field values added.
354 The method has no return value.
356 =over 4
358 =item C<$mappings>
360 Arrayref of mappings containing arrayrefs in the format
361 [C<$target>, C<$options>] where C<$target> is the name of the target field and
362 C<$options> is a hashref containing processing directives for this particular
363 mapping.
365 =item C<$data>
367 The source data from a MARC record field.
369 =item C<$record_document>
371 Hashref representing the Elasticsearch document on which mappings should be
372 applied.
374 =item C<$altscript>
376 A boolean value indicating whether an alternate script presentation is being
377 processed.
379 =back
381 =cut
383 sub _process_mappings {
384 my ($_self, $mappings, $data, $record_document, $altscript) = @_;
385 foreach my $mapping (@{$mappings}) {
386 my ($target, $options) = @{$mapping};
388 # Don't process sort fields for alternate scripts
389 my $sort = $target =~ /__sort$/;
390 if ($sort && $altscript) {
391 next;
394 # Copy (scalar) data since can have multiple targets
395 # with differing options for (possibly) mutating data
396 # so need a different copy for each
397 my $_data = $data;
398 $record_document->{$target} //= [];
399 if (defined $options->{substr}) {
400 my ($start, $length) = @{$options->{substr}};
401 $_data = length($data) > $start ? substr $data, $start, $length : '';
403 if (defined $options->{value_callbacks}) {
404 $_data = reduce { $b->($a) } ($_data, @{$options->{value_callbacks}});
406 if (defined $options->{property}) {
407 $_data = {
408 $options->{property} => $_data
411 push @{$record_document->{$target}}, $_data;
415 =head2 marc_records_to_documents($marc_records)
417 my @record_documents = $self->marc_records_to_documents($marc_records);
419 Using mappings stored in database convert C<$marc_records> to Elasticsearch documents.
421 Returns array of hash references, representing Elasticsearch documents,
422 acceptable as body payload in C<Search::Elasticsearch> requests.
424 =over 4
426 =item C<$marc_documents>
428 Reference to array of C<MARC::Record> objects to be converted to Elasticsearch documents.
430 =back
432 =cut
434 sub marc_records_to_documents {
435 my ($self, $records) = @_;
436 my $rules = $self->_get_marc_mapping_rules();
437 my $control_fields_rules = $rules->{control_fields};
438 my $data_fields_rules = $rules->{data_fields};
439 my $marcflavour = lc C4::Context->preference('marcflavour');
440 my $use_array = C4::Context->preference('ElasticsearchMARCFormat') eq 'ARRAY';
442 my @record_documents;
444 foreach my $record (@{$records}) {
445 my $record_document = {};
446 my $mappings = $rules->{leader};
447 if ($mappings) {
448 $self->_process_mappings($mappings, $record->leader(), $record_document, 0);
450 foreach my $field ($record->fields()) {
451 if ($field->is_control_field()) {
452 my $mappings = $control_fields_rules->{$field->tag()};
453 if ($mappings) {
454 $self->_process_mappings($mappings, $field->data(), $record_document, 0);
457 else {
458 my $tag = $field->tag();
459 # Handle alternate scripts in MARC 21
460 my $altscript = 0;
461 if ($marcflavour eq 'marc21' && $tag eq '880') {
462 my $sub6 = $field->subfield('6');
463 if ($sub6 =~ /^(...)-\d+/) {
464 $tag = $1;
465 $altscript = 1;
469 my $data_field_rules = $data_fields_rules->{$tag};
471 if ($data_field_rules) {
472 my $subfields_mappings = $data_field_rules->{subfields};
473 my $wildcard_mappings = $subfields_mappings->{'*'};
474 foreach my $subfield ($field->subfields()) {
475 my ($code, $data) = @{$subfield};
476 my $mappings = $subfields_mappings->{$code} // [];
477 if ($wildcard_mappings) {
478 $mappings = [@{$mappings}, @{$wildcard_mappings}];
480 if (@{$mappings}) {
481 $self->_process_mappings($mappings, $data, $record_document, $altscript);
485 my $subfields_join_mappings = $data_field_rules->{subfields_join};
486 if ($subfields_join_mappings) {
487 foreach my $subfields_group (keys %{$subfields_join_mappings}) {
488 # Map each subfield to values, remove empty values, join with space
489 my $data = join(
490 ' ',
491 grep(
493 map { join(' ', $field->subfield($_)) } split(//, $subfields_group)
496 if ($data) {
497 $self->_process_mappings($subfields_join_mappings->{$subfields_group}, $data, $record_document, $altscript);
504 foreach my $field (keys %{$rules->{defaults}}) {
505 unless (defined $record_document->{$field}) {
506 $record_document->{$field} = $rules->{defaults}->{$field};
509 foreach my $field (@{$rules->{sum}}) {
510 if (defined $record_document->{$field}) {
511 # TODO: validate numeric? filter?
512 # TODO: Or should only accept fields without nested values?
513 # TODO: Quick and dirty, improve if needed
514 $record_document->{$field} = sum0(grep { !ref($_) && m/\d+(\.\d+)?/} @{$record_document->{$field}});
517 # Index all applicable ISBN forms (ISBN-10 and ISBN-13 with and without dashes)
518 foreach my $field (@{$rules->{isbn}}) {
519 if (defined $record_document->{$field}) {
520 my @isbns = ();
521 foreach my $input_isbn (@{$record_document->{$field}}) {
522 my $isbn = Business::ISBN->new($input_isbn);
523 if (defined $isbn && $isbn->is_valid) {
524 my $isbn13 = $isbn->as_isbn13->as_string;
525 push @isbns, $isbn13;
526 $isbn13 =~ s/\-//g;
527 push @isbns, $isbn13;
529 my $isbn10 = $isbn->as_isbn10;
530 if ($isbn10) {
531 $isbn10 = $isbn10->as_string;
532 push @isbns, $isbn10;
533 $isbn10 =~ s/\-//g;
534 push @isbns, $isbn10;
536 } else {
537 push @isbns, $input_isbn;
540 $record_document->{$field} = \@isbns;
544 # Remove duplicate values and collapse sort fields
545 foreach my $field (keys %{$record_document}) {
546 if (ref($record_document->{$field}) eq 'ARRAY') {
547 @{$record_document->{$field}} = do {
548 my %seen;
549 grep { !$seen{ref($_) eq 'HASH' && defined $_->{input} ? $_->{input} : $_}++ } @{$record_document->{$field}};
551 if ($field =~ /__sort$/) {
552 # Make sure to keep the sort field length sensible. 255 was chosen as a nice round value.
553 $record_document->{$field} = [substr(join(' ', @{$record_document->{$field}}), 0, 255)];
558 # TODO: Perhaps should check if $records_document non empty, but really should never be the case
559 $record->encoding('UTF-8');
560 if ($use_array) {
561 $record_document->{'marc_data_array'} = $self->_marc_to_array($record);
562 $record_document->{'marc_format'} = 'ARRAY';
563 } else {
564 my @warnings;
566 # Temporarily intercept all warn signals (MARC::Record carps when record length > 99999)
567 local $SIG{__WARN__} = sub {
568 push @warnings, $_[0];
570 $record_document->{'marc_data'} = encode_base64(encode('UTF-8', $record->as_usmarc()));
572 if (@warnings) {
573 # Suppress warnings if record length exceeded
574 unless (substr($record->leader(), 0, 5) eq '99999') {
575 foreach my $warning (@warnings) {
576 carp $warning;
579 $record_document->{'marc_data'} = $record->as_xml_record($marcflavour);
580 $record_document->{'marc_format'} = 'MARCXML';
582 else {
583 $record_document->{'marc_format'} = 'base64ISO2709';
586 my $id = $record->subfield('999', 'c');
587 push @record_documents, [$id, $record_document];
589 return \@record_documents;
592 =head2 _marc_to_array($record)
594 my @fields = _marc_to_array($record)
596 Convert a MARC::Record to an array modeled after MARC-in-JSON
597 (see https://github.com/marc4j/marc4j/wiki/MARC-in-JSON-Description)
599 =over 4
601 =item C<$record>
603 A MARC::Record object
605 =back
607 =cut
609 sub _marc_to_array {
610 my ($self, $record) = @_;
612 my $data = {
613 leader => $record->leader(),
614 fields => []
616 for my $field ($record->fields()) {
617 my $tag = $field->tag();
618 if ($field->is_control_field()) {
619 push @{$data->{fields}}, {$tag => $field->data()};
620 } else {
621 my $subfields = ();
622 foreach my $subfield ($field->subfields()) {
623 my ($code, $contents) = @{$subfield};
624 push @{$subfields}, {$code => $contents};
626 push @{$data->{fields}}, {
627 $tag => {
628 ind1 => $field->indicator(1),
629 ind2 => $field->indicator(2),
630 subfields => $subfields
635 return $data;
638 =head2 _array_to_marc($data)
640 my $record = _array_to_marc($data)
642 Convert an array modeled after MARC-in-JSON to a MARC::Record
644 =over 4
646 =item C<$data>
648 An array modeled after MARC-in-JSON
649 (see https://github.com/marc4j/marc4j/wiki/MARC-in-JSON-Description)
651 =back
653 =cut
655 sub _array_to_marc {
656 my ($self, $data) = @_;
658 my $record = MARC::Record->new();
660 $record->leader($data->{leader});
661 for my $field (@{$data->{fields}}) {
662 my $tag = (keys %{$field})[0];
663 $field = $field->{$tag};
664 my $marc_field;
665 if (ref($field) eq 'HASH') {
666 my @subfields;
667 foreach my $subfield (@{$field->{subfields}}) {
668 my $code = (keys %{$subfield})[0];
669 push @subfields, $code;
670 push @subfields, $subfield->{$code};
672 $marc_field = MARC::Field->new($tag, $field->{ind1}, $field->{ind2}, @subfields);
673 } else {
674 $marc_field = MARC::Field->new($tag, $field)
676 $record->append_fields($marc_field);
679 return $record;
682 =head2 _field_mappings($facet, $suggestible, $sort, $search, $target_name, $target_type, $range)
684 my @mappings = _field_mappings($facet, $suggestible, $sort, $search, $target_name, $target_type, $range)
686 Get mappings, an internal data structure later used by
687 L<_process_mappings($mappings, $data, $record_document, $altscript)> to process MARC target
688 data for a MARC mapping.
690 The returned C<$mappings> is not to to be confused with mappings provided by
691 C<_foreach_mapping>, rather this sub accepts properties from a mapping as
692 provided by C<_foreach_mapping> and expands it to this internal data structure.
693 In the caller context (C<_get_marc_mapping_rules>) the returned C<@mappings>
694 is then applied to each MARC target (leader, control field data, subfield or
695 joined subfields) and integrated into the mapping rules data structure used in
696 C<marc_records_to_documents> to transform MARC records into Elasticsearch
697 documents.
699 =over 4
701 =item C<$facet>
703 Boolean indicating whether to create a facet field for this mapping.
705 =item C<$suggestible>
707 Boolean indicating whether to create a suggestion field for this mapping.
709 =item C<$sort>
711 Boolean indicating whether to create a sort field for this mapping.
713 =item C<$search>
715 Boolean indicating whether to create a search field for this mapping.
717 =item C<$target_name>
719 Elasticsearch document target field name.
721 =item C<$target_type>
723 Elasticsearch document target field type.
725 =item C<$range>
727 An optional range as a string in the format "<START>-<END>" or "<START>",
728 where "<START>" and "<END>" are integers specifying a range that will be used
729 for extracting a substring from MARC data as Elasticsearch field target value.
731 The first character position is "0", and the range is inclusive,
732 so "0-2" means the first three characters of MARC data.
734 If only "<START>" is provided only one character at position "<START>" will
735 be extracted.
737 =back
739 =cut
741 sub _field_mappings {
742 my ($_self, $facet, $suggestible, $sort, $search, $target_name, $target_type, $range) = @_;
743 my %mapping_defaults = ();
744 my @mappings;
746 my $substr_args = undef;
747 if (defined $range) {
748 # TODO: use value_callback instead?
749 my ($start, $end) = map(int, split /-/, $range, 2);
750 $substr_args = [$start];
751 push @{$substr_args}, (defined $end ? $end - $start + 1 : 1);
753 my $default_options = {};
754 if ($substr_args) {
755 $default_options->{substr} = $substr_args;
758 # TODO: Should probably have per type value callback/hook
759 # but hard code for now
760 if ($target_type eq 'boolean') {
761 $default_options->{value_callbacks} //= [];
762 push @{$default_options->{value_callbacks}}, sub {
763 my ($value) = @_;
764 # Trim whitespace at both ends
765 $value =~ s/^\s+|\s+$//g;
766 return $value ? 'true' : 'false';
770 if ($search) {
771 my $mapping = [$target_name, $default_options];
772 push @mappings, $mapping;
775 my @suffixes = ();
776 push @suffixes, 'facet' if $facet;
777 push @suffixes, 'suggestion' if $suggestible;
778 push @suffixes, 'sort' if !defined $sort || $sort;
780 foreach my $suffix (@suffixes) {
781 my $mapping = ["${target_name}__$suffix"];
782 # TODO: Hack, fix later in less hideous manner
783 if ($suffix eq 'suggestion') {
784 push @{$mapping}, {%{$default_options}, property => 'input'};
786 else {
787 push @{$mapping}, $default_options;
789 push @mappings, $mapping;
791 return @mappings;
794 =head2 _get_marc_mapping_rules
796 my $mapping_rules = $self->_get_marc_mapping_rules()
798 Generates rules from mappings stored in database for MARC records to Elasticsearch JSON document conversion.
800 Since field retrieval is slow in C<MARC::Records> (all fields are itereted through for
801 each call to C<MARC::Record>->field) we create an optimized structure of mapping
802 rules keyed by MARC field tags holding all the mapping rules for that particular tag.
804 We can then iterate through all MARC fields for each record and apply all relevant
805 rules once per fields instead of retreiving fields multiple times for each mapping rule
806 which is terribly slow.
808 =cut
810 # TODO: This structure can be used for processing multiple MARC::Records so is currently
811 # rebuilt for each batch. Since it is cacheable it could also be stored in an in
812 # memory cache which it is currently not. The performance gain of caching
813 # would probably be marginal, but to do this could be a further improvement.
815 sub _get_marc_mapping_rules {
816 my ($self) = @_;
817 my $marcflavour = lc C4::Context->preference('marcflavour');
818 my $field_spec_regexp = qr/^([0-9]{3})([()0-9a-zA-Z]+)?(?:_\/(\d+(?:-\d+)?))?$/;
819 my $leader_regexp = qr/^leader(?:_\/(\d+(?:-\d+)?))?$/;
820 my $rules = {
821 'leader' => [],
822 'control_fields' => {},
823 'data_fields' => {},
824 'sum' => [],
825 'isbn' => [],
826 'defaults' => {}
829 $self->_foreach_mapping(sub {
830 my ($name, $type, $facet, $suggestible, $sort, $search, $marc_type, $marc_field) = @_;
831 return if $marc_type ne $marcflavour;
833 if ($type eq 'sum') {
834 push @{$rules->{sum}}, $name;
836 elsif ($type eq 'isbn') {
837 push @{$rules->{isbn}}, $name;
839 elsif ($type eq 'boolean') {
840 # boolean gets special handling, if value doesn't exist for a field,
841 # it is set to false
842 $rules->{defaults}->{$name} = 'false';
845 if ($marc_field =~ $field_spec_regexp) {
846 my $field_tag = $1;
848 my @subfields;
849 my @subfield_groups;
850 # Parse and separate subfields form subfield groups
851 if (defined $2) {
852 my $subfield_group = '';
853 my $open_group = 0;
855 foreach my $token (split //, $2) {
856 if ($token eq "(") {
857 if ($open_group) {
858 Koha::Exceptions::Elasticsearch::MARCFieldExprParseError->throw(
859 "Unmatched opening parenthesis for $marc_field"
862 else {
863 $open_group = 1;
866 elsif ($token eq ")") {
867 if ($open_group) {
868 if ($subfield_group) {
869 push @subfield_groups, $subfield_group;
870 $subfield_group = '';
872 $open_group = 0;
874 else {
875 Koha::Exceptions::Elasticsearch::MARCFieldExprParseError->throw(
876 "Unmatched closing parenthesis for $marc_field"
880 elsif ($open_group) {
881 $subfield_group .= $token;
883 else {
884 push @subfields, $token;
888 else {
889 push @subfields, '*';
892 my $range = defined $3 ? $3 : undef;
893 my @mappings = $self->_field_mappings($facet, $suggestible, $sort, $search, $name, $type, $range);
894 if ($field_tag < 10) {
895 $rules->{control_fields}->{$field_tag} //= [];
896 push @{$rules->{control_fields}->{$field_tag}}, @mappings;
898 else {
899 $rules->{data_fields}->{$field_tag} //= {};
900 foreach my $subfield (@subfields) {
901 $rules->{data_fields}->{$field_tag}->{subfields}->{$subfield} //= [];
902 push @{$rules->{data_fields}->{$field_tag}->{subfields}->{$subfield}}, @mappings;
904 foreach my $subfield_group (@subfield_groups) {
905 $rules->{data_fields}->{$field_tag}->{subfields_join}->{$subfield_group} //= [];
906 push @{$rules->{data_fields}->{$field_tag}->{subfields_join}->{$subfield_group}}, @mappings;
910 elsif ($marc_field =~ $leader_regexp) {
911 my $range = defined $1 ? $1 : undef;
912 my @mappings = $self->_field_mappings($facet, $suggestible, $sort, $search, $name, $type, $range);
913 push @{$rules->{leader}}, @mappings;
915 else {
916 Koha::Exceptions::Elasticsearch::MARCFieldExprParseError->throw(
917 "Invalid MARC field expression: $marc_field"
921 return $rules;
924 =head2 _foreach_mapping
926 $self->_foreach_mapping(
927 sub {
928 my ( $name, $type, $facet, $suggestible, $sort, $marc_type,
929 $marc_field )
930 = @_;
931 return unless $marc_type eq 'marc21';
932 print "Data comes from: " . $marc_field . "\n";
936 This allows you to apply a function to each entry in the elasticsearch mappings
937 table, in order to build the mappings for whatever is needed.
939 In the provided function, the files are:
941 =over 4
943 =item C<$name>
945 The field name for elasticsearch (corresponds to the 'mapping' column in the
946 database.
948 =item C<$type>
950 The type for this value, e.g. 'string'.
952 =item C<$facet>
954 True if this value should be facetised. This only really makes sense if the
955 field is understood by the facet processing code anyway.
957 =item C<$sort>
959 True if this is a field that a) needs special sort handling, and b) if it
960 should be sorted on. False if a) but not b). Undef if not a). This allows,
961 for example, author to be sorted on but not everything marked with "author"
962 to be included in that sort.
964 =item C<$marc_type>
966 A string that indicates the MARC type that this mapping is for, e.g. 'marc21',
967 'unimarc', 'normarc'.
969 =item C<$marc_field>
971 A string that describes the MARC field that contains the data to extract.
972 These are of a form suited to Catmandu's MARC fixers.
974 =back
976 =cut
978 sub _foreach_mapping {
979 my ( $self, $sub ) = @_;
981 # TODO use a caching framework here
982 my $search_fields = Koha::Database->schema->resultset('SearchField')->search(
984 'search_marc_map.index_name' => $self->index,
986 { join => { search_marc_to_fields => 'search_marc_map' },
987 '+select' => [
988 'search_marc_to_fields.facet',
989 'search_marc_to_fields.suggestible',
990 'search_marc_to_fields.sort',
991 'search_marc_to_fields.search',
992 'search_marc_map.marc_type',
993 'search_marc_map.marc_field',
995 '+as' => [
996 'facet',
997 'suggestible',
998 'sort',
999 'search',
1000 'marc_type',
1001 'marc_field',
1006 while ( my $search_field = $search_fields->next ) {
1007 $sub->(
1008 # Force lower case on indexed field names for case insensitive
1009 # field name searches
1010 lc($search_field->name),
1011 $search_field->type,
1012 $search_field->get_column('facet'),
1013 $search_field->get_column('suggestible'),
1014 $search_field->get_column('sort'),
1015 $search_field->get_column('search'),
1016 $search_field->get_column('marc_type'),
1017 $search_field->get_column('marc_field'),
1022 =head2 process_error
1024 die process_error($@);
1026 This parses an Elasticsearch error message and produces a human-readable
1027 result from it. This result is probably missing all the useful information
1028 that you might want in diagnosing an issue, so the warning is also logged.
1030 Note that currently the resulting message is not internationalised. This
1031 will happen eventually by some method or other.
1033 =cut
1035 sub process_error {
1036 my ($self, $msg) = @_;
1038 warn $msg; # simple logging
1040 # This is super-primitive
1041 return "Unable to understand your search query, please rephrase and try again.\n" if $msg =~ /ParseException/;
1043 return "Unable to perform your search. Please try again.\n";
1046 =head2 _read_configuration
1048 my $conf = _read_configuration();
1050 Reads the I<configuration file> and returns a hash structure with the
1051 configuration information. It raises an exception if mandatory entries
1052 are missing.
1054 The hashref structure has the following form:
1057 'nodes' => ['127.0.0.1:9200', 'anotherserver:9200'],
1058 'index_name' => 'koha_instance',
1061 This is configured by the following in the C<config> block in koha-conf.xml:
1063 <elasticsearch>
1064 <server>127.0.0.1:9200</server>
1065 <server>anotherserver:9200</server>
1066 <index_name>koha_instance</index_name>
1067 </elasticsearch>
1069 =cut
1071 sub _read_configuration {
1073 my $configuration;
1075 my $conf = C4::Context->config('elasticsearch');
1076 Koha::Exceptions::Config::MissingEntry->throw(
1077 "Missing 'elasticsearch' block in config file")
1078 unless defined $conf;
1080 if ( $conf && $conf->{server} ) {
1081 my $nodes = $conf->{server};
1082 if ( ref($nodes) eq 'ARRAY' ) {
1083 $configuration->{nodes} = $nodes;
1085 else {
1086 $configuration->{nodes} = [$nodes];
1089 else {
1090 Koha::Exceptions::Config::MissingEntry->throw(
1091 "Missing 'server' entry in config file for elasticsearch");
1094 if ( defined $conf->{index_name} ) {
1095 $configuration->{index_name} = $conf->{index_name};
1097 else {
1098 Koha::Exceptions::Config::MissingEntry->throw(
1099 "Missing 'index_name' entry in config file for elasticsearch");
1102 return $configuration;
1105 =head2 get_facetable_fields
1107 my @facetable_fields = Koha::SearchEngine::Elasticsearch->get_facetable_fields();
1109 Returns the list of Koha::SearchFields marked to be faceted in the ES configuration
1111 =cut
1113 sub get_facetable_fields {
1114 my ($self) = @_;
1116 # These should correspond to the ES field names, as opposed to the CCL
1117 # things that zebra uses.
1118 my @search_field_names = qw( author itype location su-geo title-series subject ccode holdingbranch homebranch ln );
1119 my @faceted_fields = Koha::SearchFields->search(
1120 { name => { -in => \@search_field_names }, facet_order => { '!=' => undef } }, { order_by => ['facet_order'] }
1122 my @not_faceted_fields = Koha::SearchFields->search(
1123 { name => { -in => \@search_field_names }, facet_order => undef }, { order_by => ['facet_order'] }
1125 # This could certainly be improved
1126 return ( @faceted_fields, @not_faceted_fields );
1131 __END__
1133 =head1 AUTHOR
1135 =over 4
1137 =item Chris Cormack C<< <chrisc@catalyst.net.nz> >>
1139 =item Robin Sheat C<< <robin@catalyst.net.nz> >>
1141 =item Jonathan Druart C<< <jonathan.druart@bugs.koha-community.org> >>
1143 =back
1145 =cut