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();
88 # 20 is the default number of results per page
89 $paging{limit} = $count || 20;
90 # ES/Catmandu doesn't want pages, it wants a record to start from.
91 if (exists $options{offset}) {
92 $paging{start} = $options{offset};
94 $page = (!defined($page) || ($page <= 0)) ? 0 : $page - 1;
95 $paging{start} = $page * $paging{limit};
98 Catmandu::Store::ElasticSearch->new(
101 ) unless $self->store;
103 $self->store->bag->search( %$query, %paging );
106 die $self->process_error($@);
113 my $count = $searcher->count($query);
115 This mimics a search request, but just gets the result count instead. That's
116 faster than pulling all the data in, usually.
121 my ( $self, $query ) = @_;
123 my $params = $self->get_elasticsearch_params();
125 Catmandu::Store::ElasticSearch->new( %$params, trace_calls => 0, ) )
128 my $search = $self->store->bag->search( %$query);
129 my $count = $search->total() || 0;
135 my ( $error, $results, $facets ) = $search->search_compat(
136 $query, $simple_query, \@sort_by, \@servers,
137 $results_per_page, $offset, $expanded_facet, $branches,
141 A search interface somewhat compatible with L<C4::Search->getRecords>. Anything
142 that is returned in the query created by build_query_compat will probably
143 get ignored here, along with some other things (like C<@servers>.)
149 $self, $query, $simple_query, $sort_by,
150 $servers, $results_per_page, $offset, $expanded_facet,
151 $branches, $query_type, $scan
154 if ( !defined $offset or $offset < 0 ) {
157 $options{offset} = $offset;
158 $options{expanded_facet} = $expanded_facet;
159 my $results = $self->search($query, undef, $results_per_page, %options);
161 # Convert each result into a MARC::Record
163 # opac-search expects results to be put in the
164 # right place in the array, according to $offset
167 $records[$index++] = $self->decode_record_from_result(@_);
169 # consumers of this expect a name-spaced result, we provide the default
172 $result{biblioserver}{hits} = $results->total;
173 $result{biblioserver}{RECORDS} = \@records;
174 return (undef, \%result, $self->_convert_facets($results->{aggregations}, $expanded_facet));
177 =head2 search_auth_compat
179 my ( $results, $total ) =
180 $searcher->search_auth_compat( $query, $page, $count, %options );
182 This has a similar calling convention to L<search>, however it returns its
183 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
187 sub search_auth_compat {
191 my $database = Koha::Database->new();
192 my $schema = $database->schema();
193 my $res = $self->search(@_);
194 my $bib_searcher = Koha::SearchEngine::Elasticsearch::Search->new({index => 'biblios'});
200 # I wonder if these should be real values defined in the mapping
201 # rather than hard-coded conversions.
203 # Handle legacy nested arrays indexed with splitting enabled.
204 my $authid = $record->{ 'Local-number' }[0];
205 $authid = @$authid[0] if (ref $authid eq 'ARRAY');
207 $result{authid} = $authid;
209 # TODO put all this info into the record at index time so we
210 # don't have to go and sort it all out now.
211 my $authtypecode = $record->{authtype};
212 my $rs = $schema->resultset('AuthType')
213 ->search( { authtypecode => $authtypecode } );
215 # FIXME there's an assumption here that we will get a result.
216 # the original code also makes an assumption that some provided
217 # authtypecode may sometimes be used instead of the one stored
218 # with the record. It's not documented why this is the case, so
219 # it's not reproduced here yet.
220 my $authtype = $rs->single;
221 my $auth_tag_to_report = $authtype ? $authtype->auth_tag_to_report : "";
222 my $marc = $self->decode_record_from_result(@_);
223 my $mainentry = $marc->field($auth_tag_to_report);
226 foreach ( $mainentry->subfields() ) {
227 $reported_tag .= '$' . $_->[0] . $_->[1];
230 # Turn the resultset into a hash
231 $result{authtype} = $authtype ? $authtype->authtypetext : $authtypecode;
232 $result{reported_tag} = $reported_tag;
234 # Reimplementing BuildSummary is out of scope because it'll be hard
236 C4::AuthoritiesMarc::BuildSummary( $marc, $result{authid},
238 $result{used} = $self->count_auth_use($bib_searcher, $authid);
239 push @records, \%result;
242 return ( \@records, $res->total );
245 =head2 count_auth_use
247 my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
249 This runs a search to determine the number of records that reference the
250 specified authid. C<$bib_searcher> must be something compatible with
251 elasticsearch, as the query is built in this function.
256 my ($self, $bib_searcher, $authid) = @_;
261 # query => { match_all => {} },
262 filter => { term => { an => $authid } }
266 $bib_searcher->count($query);
269 =head2 simple_search_compat
271 my ( $error, $marcresults, $total_hits ) =
272 $searcher->simple_search( $query, $offset, $max_results, %options );
274 This is a simpler interface to the searching, intended to be similar enough to
275 L<C4::Search::SimpleSearch>.
283 A thing to search for. It could be a simple string, or something constructed
284 with the appropriate QueryBuilder module.
288 How many results to skip from the start of the results.
290 =item C<$max_results>
292 The max number of results to return. The default is 100 (because unlimited
293 is a pretty terrible thing to do.)
297 These options are unused by Elasticsearch
307 if something went wrong, this'll contain some kind of error
310 =item C<$marcresults>
312 an arrayref of MARC::Records (note that this is different from the
313 L<C4::Search> version which will return plain XML, but too bad.)
317 the total number of results that this search could have returned.
323 sub simple_search_compat {
324 my ($self, $query, $offset, $max_results) = @_;
326 return ('No query entered', undef, undef) unless $query;
329 $offset = 0 if not defined $offset or $offset < 0;
330 $options{offset} = $offset;
331 $max_results //= 100;
333 unless (ref $query) {
334 # We'll push it through the query builder to sanitise everything.
335 my $qb = Koha::SearchEngine::QueryBuilder->new({index => $self->index});
336 (undef,$query) = $qb->build_query_compat(undef, [$query]);
338 my $results = $self->search($query, undef, $max_results, %options);
341 my $marc = $self->decode_record_from_result(@_);
342 push @records, $marc;
344 return (undef, \@records, $results->total);
347 =head2 extract_biblionumber
349 my $biblionumber = $searcher->extract_biblionumber( $searchresult );
351 $searchresult comes from simple_search_compat.
353 Returns the biblionumber from the search result record.
357 sub extract_biblionumber {
358 my ( $self, $searchresultrecord ) = @_;
359 return Koha::SearchEngine::Search::extract_biblionumber( $searchresultrecord );
362 =head2 decode_record_from_result
363 my $marc_record = $self->decode_record_from_result(@result);
365 Extracts marc data from Elasticsearch result and decodes to MARC::Record object
369 sub decode_record_from_result {
370 # Result is passed in as array, will get flattened
371 # and first element will be $result
372 my ( $self, $result ) = @_;
373 if ($result->{marc_format} eq 'base64ISO2709') {
374 return MARC::Record->new_from_usmarc(decode_base64($result->{marc_data}));
376 elsif ($result->{marc_format} eq 'MARCXML') {
377 return MARC::Record->new_from_xml($result->{marc_data}, 'UTF-8', uc C4::Context->preference('marcflavour'));
380 Koha::Exceptions::Elasticsearch->throw("Missing marc_format field in Elasticsearch result");
384 =head2 max_result_window
386 Returns the maximum number of results that can be fetched
388 This directly requests Elasticsearch for the setting index.max_result_window (or
389 the default value for this setting in case it is not set)
393 sub max_result_window {
397 Catmandu::Store::ElasticSearch->new(%{ $self->get_elasticsearch_params })
398 ) unless $self->store;
400 my $index_name = $self->store->index_name;
401 my $settings = $self->store->es->indices->get_settings(
402 index => $index_name,
403 params => { include_defaults => 1, flat_settings => 1 },
406 my $max_result_window = $settings->{$index_name}->{settings}->{'index.max_result_window'};
407 $max_result_window //= $settings->{$index_name}->{defaults}->{'index.max_result_window'};
409 return $max_result_window;
412 =head2 _convert_facets
414 my $koha_facets = _convert_facets($es_facets, $expanded_facet);
416 Converts elasticsearch facets types to the form that Koha expects.
417 It expects the ES facet name to match the Koha type, for example C<itype>,
418 C<au>, C<su-to>, etc.
420 C<$expanded_facet> is the facet that we want to show FacetMaxCount entries for, rather
421 than just 5 like normal.
425 sub _convert_facets {
426 my ( $self, $es, $exp_facet ) = @_;
430 # These should correspond to the ES field names, as opposed to the CCL
431 # things that zebra uses.
432 # TODO let the library define the order using the interface.
433 my %type_to_label = (
434 author => { order => 1, label => 'Authors', },
435 itype => { order => 2, label => 'ItemTypes', },
436 location => { order => 3, label => 'Location', },
437 'su-geo' => { order => 4, label => 'Places', },
438 se => { order => 5, label => 'Series', },
439 subject => { order => 6, label => 'Topics', },
440 ccode => { order => 7, label => 'CollectionCodes',},
441 holdingbranch => { order => 8, label => 'HoldingLibrary' },
442 homebranch => { order => 9, label => 'HomeLibrary' }
445 # We also have some special cases, e.g. itypes that need to show the
446 # value rather than the code.
447 my @itypes = Koha::ItemTypes->search;
448 my @libraries = Koha::Libraries->search;
449 my $library_names = { map { $_->branchcode => $_->branchname } @libraries };
450 my @locations = Koha::AuthorisedValues->search( { category => 'LOC' } );
451 my $opac = C4::Context->interface eq 'opac' ;
453 itype => { map { $_->itemtype => $_->description } @itypes },
454 location => { map { $_->authorised_value => ( $opac ? ( $_->lib_opac || $_->lib ) : $_->lib ) } @locations },
455 holdingbranch => $library_names,
456 homebranch => $library_names
460 while ( my ( $type, $data ) = each %$es ) {
461 next if !exists( $type_to_label{$type} );
463 # We restrict to the most popular $limit !results
464 my $limit = ( $type eq $exp_facet ) ? C4::Context->preference('FacetMaxCount') : 5;
466 type_id => $type . '_id',
468 expandable => ( $type ne $exp_facet )
469 && ( @{ $data->{buckets} } > $limit ),
470 "type_label_$type_to_label{$type}{label}" => 1,
471 type_link_value => $type,
472 order => $type_to_label{$type}{order},
474 $limit = @{ $data->{buckets} } if ( $limit > @{ $data->{buckets} } );
475 foreach my $term ( @{ $data->{buckets} }[ 0 .. $limit - 1 ] ) {
476 my $t = $term->{key};
477 my $c = $term->{doc_count};
479 if ( exists( $special{$type} ) ) {
480 $label = $special{$type}->{$t} // $t;
485 push @{ $facet->{facets} }, {
487 facet_link_value => $t,
488 facet_title_value => $t . " ($c)",
489 facet_label_value => $label, # TODO either truncate this,
490 # or make the template do it like it should anyway
491 type_link_value => $type,
494 push @facets, $facet if exists $facet->{facets};
497 @facets = sort { $a->{order} cmp $b->{order} } @facets;