1 package Koha
::SearchEngine
::Elasticsearch
::Search
;
3 # Copyright 2014 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
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.
22 Koha::SearchEngine::Elasticsearch::Search - search functions for Elasticsearch
27 Koha::SearchEngine::Elasticsearch::Search->new( { index => $index } );
28 my $builder = Koha::SearchEngine::Elasticsearch::QueryBuilder->new(
29 { index => $index } );
30 my $query = $builder->build_query('perl');
31 my $results = $searcher->search($query);
32 print "There were " . $results->total . " results.\n";
43 use base
qw(Koha::SearchEngine::Elasticsearch);
45 use C4
::AuthoritiesMarc
;
47 use Koha
::AuthorisedValues
;
48 use Koha
::SearchEngine
::QueryBuilder
;
49 use Koha
::SearchEngine
::Search
;
50 use Koha
::Exceptions
::Elasticsearch
;
52 use Catmandu
::Store
::ElasticSearch
;
54 use Data
::Dumper
; #TODO remove
58 Koha
::SearchEngine
::Elasticsearch
::Search
->mk_accessors(qw( store ));
62 my $results = $searcher->search($query, $page, $count, %options);
64 Run a search using the query. It'll return C<$count> results, starting at page
65 C<$page> (C<$page> counts from 1, anything less that, or C<undef> becomes 1.)
66 C<$count> is also the number of entries on a page.
68 C<%options> is a hash containing extra options:
74 If provided, this overrides the C<$page> value, and specifies the record as
75 an offset (i.e. the number of the record to start with), rather than a page.
84 my ($self, $query, $page, $count, %options) = @_;
86 my $params = $self->get_elasticsearch_params();
87 # 20 is the default number of results per page
88 $query->{size
} = $count || 20;
89 # ES doesn't want pages, it wants a record to start from.
90 if (exists $options{offset
}) {
91 $query->{from
} = $options{offset
};
93 $page = (!defined($page) || ($page <= 0)) ?
0 : $page - 1;
94 $query->{from
} = $page * $query->{size
};
96 my $elasticsearch = $self->get_elasticsearch();
98 $elasticsearch->search(
99 index => $params->{index_name
},
104 die $self->process_error($@
);
111 my $count = $searcher->count($query);
113 This mimics a search request, but just gets the result count instead. That's
114 faster than pulling all the data in, usually.
119 my ( $self, $query ) = @_;
121 my $params = $self->get_elasticsearch_params();
123 Catmandu
::Store
::ElasticSearch
->new( %$params, trace_calls
=> 0, ) )
126 my $search = $self->store->bag->search( %$query);
127 my $count = $search->total() || 0;
133 my ( $error, $results, $facets ) = $search->search_compat(
134 $query, $simple_query, \@sort_by, \@servers,
135 $results_per_page, $offset, $branches, $query_type,
139 A search interface somewhat compatible with L<C4::Search->getRecords>. Anything
140 that is returned in the query created by build_query_compat will probably
141 get ignored here, along with some other things (like C<@servers>.)
147 $self, $query, $simple_query, $sort_by,
148 $servers, $results_per_page, $offset, $branches,
152 if ( !defined $offset or $offset < 0 ) {
155 $options{offset
} = $offset;
156 my $results = $self->search($query, undef, $results_per_page, %options);
158 # Convert each result into a MARC::Record
160 # opac-search expects results to be put in the
161 # right place in the array, according to $offset
163 my $hits = $results->{'hits'};
164 foreach my $es_record (@
{$hits->{'hits'}}) {
165 $records[$index++] = $self->decode_record_from_result($es_record->{'_source'});
168 # consumers of this expect a name-spaced result, we provide the default
171 $result{biblioserver
}{hits
} = $hits->{'total'};
172 $result{biblioserver
}{RECORDS
} = \
@records;
173 return (undef, \
%result, $self->_convert_facets($results->{aggregations
}));
176 =head2 search_auth_compat
178 my ( $results, $total ) =
179 $searcher->search_auth_compat( $query, $offset, $count, $skipmetadata, %options );
181 This has a similar calling convention to L<search>, however it returns its
182 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
186 sub search_auth_compat
{
187 my ($self, $query, $offset, $count, $skipmetadata, %options) = @_;
189 if ( !defined $offset or $offset <= 0 ) {
192 # Uh, authority search uses 1-based offset..
193 $options{offset
} = $offset - 1;
194 my $database = Koha
::Database
->new();
195 my $schema = $database->schema();
196 my $res = $self->search($query, undef, $count, %options);
198 my $bib_searcher = Koha
::SearchEngine
::Elasticsearch
::Search
->new({index => 'biblios'});
200 my $hits = $res->{'hits'};
201 foreach my $es_record (@
{$hits->{'hits'}}) {
202 my $record = $es_record->{'_source'};
205 # I wonder if these should be real values defined in the mapping
206 # rather than hard-coded conversions.
208 # Handle legacy nested arrays indexed with splitting enabled.
209 my $authid = $record->{ 'local-number' }[0];
210 $authid = @
$authid[0] if (ref $authid eq 'ARRAY');
212 $result{authid
} = $authid;
214 if (!defined $skipmetadata || !$skipmetadata) {
215 # TODO put all this info into the record at index time so we
216 # don't have to go and sort it all out now.
217 my $authtypecode = $record->{authtype
};
218 my $rs = $schema->resultset('AuthType')
219 ->search( { authtypecode
=> $authtypecode } );
221 # FIXME there's an assumption here that we will get a result.
222 # the original code also makes an assumption that some provided
223 # authtypecode may sometimes be used instead of the one stored
224 # with the record. It's not documented why this is the case, so
225 # it's not reproduced here yet.
226 my $authtype = $rs->single;
227 my $auth_tag_to_report = $authtype ?
$authtype->auth_tag_to_report : "";
228 my $marc = $self->decode_record_from_result($record);
229 my $mainentry = $marc->field($auth_tag_to_report);
232 foreach ( $mainentry->subfields() ) {
233 $reported_tag .= '$' . $_->[0] . $_->[1];
236 # Turn the resultset into a hash
237 $result{authtype
} = $authtype ?
$authtype->authtypetext : $authtypecode;
238 $result{reported_tag
} = $reported_tag;
240 # Reimplementing BuildSummary is out of scope because it'll be hard
242 C4
::AuthoritiesMarc
::BuildSummary
( $marc, $result{authid
},
244 $result{used
} = $self->count_auth_use($bib_searcher, $authid);
246 push @records, \
%result;
248 return ( \
@records, $hits->{'total'} );
251 =head2 count_auth_use
253 my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
255 This runs a search to determine the number of records that reference the
256 specified authid. C<$bib_searcher> must be something compatible with
257 elasticsearch, as the query is built in this function.
262 my ($self, $bib_searcher, $authid) = @_;
267 # query => { match_all => {} },
268 filter
=> { term
=> { 'koha-auth-number' => $authid } }
272 $bib_searcher->count($query);
275 =head2 simple_search_compat
277 my ( $error, $marcresults, $total_hits ) =
278 $searcher->simple_search( $query, $offset, $max_results, %options );
280 This is a simpler interface to the searching, intended to be similar enough to
281 L<C4::Search::SimpleSearch>.
289 A thing to search for. It could be a simple string, or something constructed
290 with the appropriate QueryBuilder module.
294 How many results to skip from the start of the results.
296 =item C<$max_results>
298 The max number of results to return. The default is 100 (because unlimited
299 is a pretty terrible thing to do.)
303 These options are unused by Elasticsearch
313 if something went wrong, this'll contain some kind of error
316 =item C<$marcresults>
318 an arrayref of MARC::Records (note that this is different from the
319 L<C4::Search> version which will return plain XML, but too bad.)
323 the total number of results that this search could have returned.
329 sub simple_search_compat
{
330 my ($self, $query, $offset, $max_results) = @_;
332 return ('No query entered', undef, undef) unless $query;
335 $offset = 0 if not defined $offset or $offset < 0;
336 $options{offset
} = $offset;
337 $max_results //= 100;
339 unless (ref $query) {
340 # We'll push it through the query builder to sanitise everything.
341 my $qb = Koha
::SearchEngine
::QueryBuilder
->new({index => $self->index});
342 (undef,$query) = $qb->build_query_compat(undef, [$query]);
344 my $results = $self->search($query, undef, $max_results, %options);
346 my $hits = $results->{'hits'};
347 foreach my $es_record (@
{$hits->{'hits'}}) {
348 push @records, $self->decode_record_from_result($es_record->{'_source'});
350 return (undef, \
@records, $hits->{'total'});
353 =head2 extract_biblionumber
355 my $biblionumber = $searcher->extract_biblionumber( $searchresult );
357 $searchresult comes from simple_search_compat.
359 Returns the biblionumber from the search result record.
363 sub extract_biblionumber
{
364 my ( $self, $searchresultrecord ) = @_;
365 return Koha
::SearchEngine
::Search
::extract_biblionumber
( $searchresultrecord );
368 =head2 decode_record_from_result
369 my $marc_record = $self->decode_record_from_result(@result);
371 Extracts marc data from Elasticsearch result and decodes to MARC::Record object
375 sub decode_record_from_result
{
376 # Result is passed in as array, will get flattened
377 # and first element will be $result
378 my ( $self, $result ) = @_;
379 if ($result->{marc_format
} eq 'base64ISO2709') {
380 return MARC
::Record
->new_from_usmarc(decode_base64
($result->{marc_data
}));
382 elsif ($result->{marc_format
} eq 'MARCXML') {
383 return MARC
::Record
->new_from_xml($result->{marc_data
}, 'UTF-8', uc C4
::Context
->preference('marcflavour'));
385 elsif ($result->{marc_format
} eq 'ARRAY') {
386 return $self->_array_to_marc($result->{marc_data_array
});
389 Koha
::Exceptions
::Elasticsearch
->throw("Missing marc_format field in Elasticsearch result");
393 =head2 max_result_window
395 Returns the maximum number of results that can be fetched
397 This directly requests Elasticsearch for the setting index.max_result_window (or
398 the default value for this setting in case it is not set)
402 sub max_result_window
{
406 Catmandu
::Store
::ElasticSearch
->new(%{ $self->get_elasticsearch_params })
407 ) unless $self->store;
409 my $index_name = $self->store->index_name;
410 my $settings = $self->store->es->indices->get_settings(
411 index => $index_name,
412 params
=> { include_defaults
=> 'true', flat_settings
=> 'true' },
415 my $max_result_window = $settings->{$index_name}->{settings
}->{'index.max_result_window'};
416 $max_result_window //= $settings->{$index_name}->{defaults
}->{'index.max_result_window'};
418 return $max_result_window;
421 =head2 _convert_facets
423 my $koha_facets = _convert_facets($es_facets);
425 Converts elasticsearch facets types to the form that Koha expects.
426 It expects the ES facet name to match the Koha type, for example C<itype>,
427 C<au>, C<su-to>, etc.
431 sub _convert_facets
{
432 my ( $self, $es, $exp_facet ) = @_;
436 # These should correspond to the ES field names, as opposed to the CCL
437 # things that zebra uses.
441 itype
=> 'ItemTypes',
442 location
=> 'Location',
443 'su-geo' => 'Places',
444 'title-series' => 'Series',
446 ccode
=> 'CollectionCodes',
447 holdingbranch
=> 'HoldingLibrary',
448 homebranch
=> 'HomeLibrary',
451 my @facetable_fields =
452 Koha
::SearchEngine
::Elasticsearch
->get_facetable_fields;
453 for my $f (@facetable_fields) {
454 next unless defined $f->facet_order;
455 $type_to_label{ $f->name } =
456 { order
=> $f->facet_order, label
=> $label{ $f->name } };
459 # We also have some special cases, e.g. itypes that need to show the
460 # value rather than the code.
461 my @itypes = Koha
::ItemTypes
->search;
462 my @libraries = Koha
::Libraries
->search;
463 my $library_names = { map { $_->branchcode => $_->branchname } @libraries };
464 my @locations = Koha
::AuthorisedValues
->search( { category
=> 'LOC' } );
465 my $opac = C4
::Context
->interface eq 'opac' ;
467 itype
=> { map { $_->itemtype => $_->description } @itypes },
468 location
=> { map { $_->authorised_value => ( $opac ?
( $_->lib_opac || $_->lib ) : $_->lib ) } @locations },
469 holdingbranch
=> $library_names,
470 homebranch
=> $library_names
474 while ( my ( $type, $data ) = each %$es ) {
475 next if !exists( $type_to_label{$type} );
477 # We restrict to the most popular $limit !results
478 my $limit = C4
::Context
->preference('FacetMaxCount');
480 type_id
=> $type . '_id',
481 "type_label_$type_to_label{$type}{label}" => 1,
482 type_link_value
=> $type,
483 order
=> $type_to_label{$type}{order
},
485 $limit = @
{ $data->{buckets
} } if ( $limit > @
{ $data->{buckets
} } );
486 foreach my $term ( @
{ $data->{buckets
} }[ 0 .. $limit - 1 ] ) {
487 my $t = $term->{key
};
488 my $c = $term->{doc_count
};
490 if ( exists( $special{$type} ) ) {
491 $label = $special{$type}->{$t} // $t;
496 push @
{ $facet->{facets
} }, {
498 facet_link_value
=> $t,
499 facet_title_value
=> $t . " ($c)",
500 facet_label_value
=> $label, # TODO either truncate this,
501 # or make the template do it like it should anyway
502 type_link_value
=> $type,
505 push @facets, $facet if exists $facet->{facets
};
508 @facets = sort { $a->{order
} <=> $b->{order
} } @facets;