Bug 28610: Elasticsearch 7 - hits.total is now an object
[koha-ffzg.git] / Koha / SearchEngine / Elasticsearch / Search.pm
index 4bc259a..fc7eda5 100644 (file)
@@ -4,18 +4,18 @@ package Koha::SearchEngine::Elasticsearch::Search;
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 3 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 =head1 NAME
 
@@ -49,11 +49,9 @@ use Koha::SearchEngine::QueryBuilder;
 use Koha::SearchEngine::Search;
 use Koha::Exceptions::Elasticsearch;
 use MARC::Record;
-use Catmandu::Store::ElasticSearch;
 use MARC::File::XML;
-use Data::Dumper; #TODO remove
-use Carp qw(cluck);
-use MIME::Base64;
+use MIME::Base64 qw( decode_base64 );
+use JSON;
 
 Koha::SearchEngine::Elasticsearch::Search->mk_accessors(qw( store ));
 
@@ -83,9 +81,8 @@ Returns
 sub search {
     my ($self, $query, $page, $count, %options) = @_;
 
-    my $params = $self->get_elasticsearch_params();
     # 20 is the default number of results per page
-    $query->{size} = $count || 20;
+    $query->{size} = $count // 20;
     # ES doesn't want pages, it wants a record to start from.
     if (exists $options{offset}) {
         $query->{from} = $options{offset};
@@ -96,13 +93,17 @@ sub search {
     my $elasticsearch = $self->get_elasticsearch();
     my $results = eval {
         $elasticsearch->search(
-            index => $params->{index_name},
+            index => $self->index_name,
+            track_total_hits => JSON::true,
             body => $query
         );
     };
     if ($@) {
         die $self->process_error($@);
     }
+    if (ref $results->{hits}->{total} eq 'HASH') {
+        $results->{hits}->{total} = $results->{hits}->{total}->{value};
+    }
     return $results;
 }
 
@@ -117,22 +118,27 @@ faster than pulling all the data in, usually.
 
 sub count {
     my ( $self, $query ) = @_;
+    my $elasticsearch = $self->get_elasticsearch();
 
-    my $params = $self->get_elasticsearch_params();
-    $self->store(
-        Catmandu::Store::ElasticSearch->new( %$params, trace_calls => 0, ) )
-      unless $self->store;
+    # TODO: Probably possible to exclude results
+    # and just return number of hits
+    my $result = $elasticsearch->search(
+        index => $self->index_name,
+        track_total_hits => JSON::true,
+        body => $query
+    );
 
-    my $search = $self->store->bag->search( %$query);
-    my $count = $search->total() || 0;
-    return $count;
+    if (ref $result->{hits}->{total} eq 'HASH') {
+        return $result->{hits}->{total}->{value};
+    }
+    return $result->{hits}->{total};
 }
 
 =head2 search_compat
 
     my ( $error, $results, $facets ) = $search->search_compat(
         $query,            $simple_query, \@sort_by,       \@servers,
-        $results_per_page, $offset,       $expanded_facet, $branches,
+        $results_per_page, $offset,       undef,           $item_types,
         $query_type,       $scan
       )
 
@@ -144,16 +150,20 @@ get ignored here, along with some other things (like C<@servers>.)
 
 sub search_compat {
     my (
-        $self,     $query,            $simple_query, $sort_by,
-        $servers,  $results_per_page, $offset,       $expanded_facet,
-        $branches, $query_type,       $scan
+        $self,       $query,            $simple_query, $sort_by,
+        $servers,    $results_per_page, $offset,       $branches,
+        $item_types, $query_type,       $scan
     ) = @_;
+
+    if ( $scan ) {
+        return $self->_aggregation_scan( $query, $results_per_page, $offset );
+    }
+
     my %options;
     if ( !defined $offset or $offset < 0 ) {
         $offset = 0;
     }
     $options{offset} = $offset;
-    $options{expanded_facet} = $expanded_facet;
     my $results = $self->search($query, undef, $results_per_page, %options);
 
     # Convert each result into a MARC::Record
@@ -171,7 +181,7 @@ sub search_compat {
     my %result;
     $result{biblioserver}{hits} = $hits->{'total'};
     $result{biblioserver}{RECORDS} = \@records;
-    return (undef, \%result, $self->_convert_facets($results->{aggregations}, $expanded_facet));
+    return (undef, \%result, $self->_convert_facets($results->{aggregations}));
 }
 
 =head2 search_auth_compat
@@ -203,12 +213,10 @@ sub search_auth_compat {
         my $record = $es_record->{'_source'};
         my %result;
 
-        # I wonder if these should be real values defined in the mapping
-        # rather than hard-coded conversions.
-        #my $record    = $_[0];
-        # Handle legacy nested arrays indexed with splitting enabled.
-        my $authid = $record->{ 'Local-number' }[0];
-        $authid = @$authid[0] if (ref $authid eq 'ARRAY');
+        # We are using the authid to create links, we should honor the authid as stored in the db, not
+        # the 001 which, in some circumstances, can contain other data
+        my $authid = $es_record->{_id};
+
 
         $result{authid} = $authid;
 
@@ -266,7 +274,7 @@ sub count_auth_use {
         query => {
             bool => {
 #                query  => { match_all => {} },
-                filter => { term      => { an => $authid } }
+                filter => { term      => { 'koha-auth-number' => $authid } }
             }
         }
     };
@@ -383,6 +391,9 @@ sub decode_record_from_result {
     elsif ($result->{marc_format} eq 'MARCXML') {
         return MARC::Record->new_from_xml($result->{marc_data}, 'UTF-8', uc C4::Context->preference('marcflavour'));
     }
+    elsif ($result->{marc_format} eq 'ARRAY') {
+        return $self->_array_to_marc($result->{marc_data_array});
+    }
     else {
         Koha::Exceptions::Elasticsearch->throw("Missing marc_format field in Elasticsearch result");
     }
@@ -400,33 +411,28 @@ the default value for this setting in case it is not set)
 sub max_result_window {
     my ($self) = @_;
 
-    $self->store(
-        Catmandu::Store::ElasticSearch->new(%{ $self->get_elasticsearch_params })
-    ) unless $self->store;
+    my $elasticsearch = $self->get_elasticsearch();
 
-    my $index_name = $self->store->index_name;
-    my $settings = $self->store->es->indices->get_settings(
-        index  => $index_name,
-        params => { include_defaults => 'true', flat_settings => 'true' },
+    my $response = $elasticsearch->indices->get_settings(
+        index => $self->index_name,
+        flat_settings => 'true',
+        include_defaults => 'true'
     );
 
-    my $max_result_window = $settings->{$index_name}->{settings}->{'index.max_result_window'};
-    $max_result_window //= $settings->{$index_name}->{defaults}->{'index.max_result_window'};
+    my $max_result_window = $response->{$self->index_name}->{settings}->{'index.max_result_window'};
+    $max_result_window //= $response->{$self->index_name}->{defaults}->{'index.max_result_window'};
 
     return $max_result_window;
 }
 
 =head2 _convert_facets
 
-    my $koha_facets = _convert_facets($es_facets, $expanded_facet);
+    my $koha_facets = _convert_facets($es_facets);
 
 Converts elasticsearch facets types to the form that Koha expects.
 It expects the ES facet name to match the Koha type, for example C<itype>,
 C<au>, C<su-to>, etc.
 
-C<$expanded_facet> is the facet that we want to show FacetMaxCount entries for, rather
-than just 5 like normal.
-
 =cut
 
 sub _convert_facets {
@@ -436,25 +442,33 @@ sub _convert_facets {
 
     # These should correspond to the ES field names, as opposed to the CCL
     # things that zebra uses.
-    # TODO let the library define the order using the interface.
-    my %type_to_label = (
-        author   => { order => 1, label => 'Authors', },
-        itype    => { order => 2, label => 'ItemTypes', },
-        location => { order => 3, label => 'Location', },
-        'su-geo' => { order => 4, label => 'Places', },
-        se       => { order => 5, label => 'Series', },
-        subject  => { order => 6, label => 'Topics', },
-        ccode    => { order => 7, label => 'CollectionCodes',},
-        holdingbranch => { order => 8, label => 'HoldingLibrary' },
-        homebranch => { order => 9, label => 'HomeLibrary' }
+    my %type_to_label;
+    my %label = (
+        author         => 'Authors',
+        itype          => 'ItemTypes',
+        location       => 'Location',
+        'su-geo'       => 'Places',
+        'title-series' => 'Series',
+        subject        => 'Topics',
+        ccode          => 'CollectionCodes',
+        holdingbranch  => 'HoldingLibrary',
+        homebranch     => 'HomeLibrary',
+        ln             => 'Language',
     );
+    my @facetable_fields =
+      Koha::SearchEngine::Elasticsearch->get_facetable_fields;
+    for my $f (@facetable_fields) {
+        next unless defined $f->facet_order;
+        $type_to_label{ $f->name } =
+          { order => $f->facet_order, label => $label{ $f->name } };
+    }
 
     # We also have some special cases, e.g. itypes that need to show the
     # value rather than the code.
-    my @itypes = Koha::ItemTypes->search;
-    my @libraries = Koha::Libraries->search;
+    my @itypes = Koha::ItemTypes->search->as_list;
+    my @libraries = Koha::Libraries->search->as_list;
     my $library_names = { map { $_->branchcode => $_->branchname } @libraries };
-    my @locations = Koha::AuthorisedValues->search( { category => 'LOC' } );
+    my @locations = Koha::AuthorisedValues->search( { category => 'LOC' } )->as_list;
     my $opac = C4::Context->interface eq 'opac' ;
     my %special = (
         itype    => { map { $_->itemtype         => $_->description } @itypes },
@@ -468,12 +482,9 @@ sub _convert_facets {
         next if !exists( $type_to_label{$type} );
 
         # We restrict to the most popular $limit !results
-        my $limit = ( $type eq $exp_facet ) ? C4::Context->preference('FacetMaxCount') : 5;
+        my $limit = C4::Context->preference('FacetMaxCount');
         my $facet = {
             type_id    => $type . '_id',
-            expand     => $type,
-            expandable => ( $type ne $exp_facet )
-              && ( @{ $data->{buckets} } > $limit ),
             "type_label_$type_to_label{$type}{label}" => 1,
             type_link_value                    => $type,
             order      => $type_to_label{$type}{order},
@@ -498,12 +509,79 @@ sub _convert_facets {
                 type_link_value => $type,
             };
         }
+        if( C4::Context->preference('FacetOrder') eq 'Alphabetical' ){
+            @{ $facet->{facets} } =
+                sort { $a->{facet_label_value} cmp $b->{facet_label_value} } @{ $facet->{facets} };
+        }
         push @facets, $facet if exists $facet->{facets};
     }
 
-    @facets = sort { $a->{order} cmp $b->{order} } @facets;
+
+    @facets = sort { $a->{order} <=> $b->{order} } @facets;
     return \@facets;
 }
 
+=head2 _aggregation_scan
+
+    my $result = $self->_aggregration_scan($query, 10, 0);
+
+Perform an aggregation request for scan purposes.
+
+=cut
+
+sub _aggregation_scan {
+    my ($self, $query, $results_per_page, $offset) = @_;
+
+    if (!scalar(keys %{$query->{aggregations}})) {
+        my %result = {
+            biblioserver => {
+                hits => 0,
+                RECORDS => undef
+            }
+        };
+        return (undef, \%result, undef);
+    }
+    my ($field) = keys %{$query->{aggregations}};
+    $query->{aggregations}{$field}{terms}{size} = 1000;
+    my $results = $self->search($query, 1, 0);
+
+    # Convert each result into a MARC::Record
+    my (@records, $index);
+    # opac-search expects results to be put in the
+    # right place in the array, according to $offset
+    $index = $offset - 1;
+
+    my $count = scalar(@{$results->{aggregations}{$field}{buckets}});
+    for (my $index = $offset; $index - $offset < $results_per_page && $index < $count; $index++) {
+        my $bucket = $results->{aggregations}{$field}{buckets}->[$index];
+        # Scan values are expressed as:
+        # - MARC21: 100a (count) and 245a (term)
+        # - UNIMARC: 200f (count) and 200a (term)
+        my $marc = MARC::Record->new;
+        $marc->encoding('UTF-8');
+        if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
+            $marc->append_fields(
+                MARC::Field->new((200, ' ',  ' ', 'f' => $bucket->{doc_count}))
+            );
+            $marc->append_fields(
+                MARC::Field->new((200, ' ',  ' ', 'a' => $bucket->{key}))
+            );
+        } else {
+            $marc->append_fields(
+                MARC::Field->new((100, ' ',  ' ', 'a' => $bucket->{doc_count}))
+            );
+            $marc->append_fields(
+                MARC::Field->new((245, ' ',  ' ', 'a' => $bucket->{key}))
+            );
+        }
+        $records[$index] = $marc->as_usmarc();
+    };
+    # consumers of this expect a namespaced result, we provide the default
+    # configuration.
+    my %result;
+    $result{biblioserver}{hits} = $count;
+    $result{biblioserver}{RECORDS} = \@records;
+    return (undef, \%result, undef);
+}
 
 1;