Bug 24902: Join different mc- limits with AND (elasticsearch)
[koha.git] / Koha / SearchEngine / Elasticsearch / Search.pm
bloba5b410e3a67110d5cc3ac655a93250d93b122df3
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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 =head1 NAME
22 Koha::SearchEngine::Elasticsearch::Search - search functions for Elasticsearch
24 =head1 SYNOPSIS
26 my $searcher =
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";
33 $results->each(sub {
34 push @hits, @_[0];
35 });
37 =head1 METHODS
39 =cut
41 use Modern::Perl;
43 use base qw(Koha::SearchEngine::Elasticsearch);
44 use C4::Context;
45 use C4::AuthoritiesMarc;
46 use Koha::ItemTypes;
47 use Koha::AuthorisedValues;
48 use Koha::SearchEngine::QueryBuilder;
49 use Koha::SearchEngine::Search;
50 use Koha::Exceptions::Elasticsearch;
51 use MARC::Record;
52 use Catmandu::Store::ElasticSearch;
53 use MARC::File::XML;
54 use Data::Dumper; #TODO remove
55 use Carp qw(cluck);
56 use MIME::Base64;
58 Koha::SearchEngine::Elasticsearch::Search->mk_accessors(qw( store ));
60 =head2 search
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:
70 =over 4
72 =item offset
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.
77 =back
79 Returns
81 =cut
83 sub search {
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};
92 } else {
93 $page = (!defined($page) || ($page <= 0)) ? 0 : $page - 1;
94 $query->{from} = $page * $query->{size};
96 my $elasticsearch = $self->get_elasticsearch();
97 my $results = eval {
98 $elasticsearch->search(
99 index => $params->{index_name},
100 body => $query
103 if ($@) {
104 die $self->process_error($@);
106 return $results;
109 =head2 count
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.
116 =cut
118 sub count {
119 my ( $self, $query ) = @_;
121 my $params = $self->get_elasticsearch_params();
122 $self->store(
123 Catmandu::Store::ElasticSearch->new( %$params, trace_calls => 0, ) )
124 unless $self->store;
126 my $search = $self->store->bag->search( %$query);
127 my $count = $search->total() || 0;
128 return $count;
131 =head2 search_compat
133 my ( $error, $results, $facets ) = $search->search_compat(
134 $query, $simple_query, \@sort_by, \@servers,
135 $results_per_page, $offset, undef, $item_types,
136 $query_type, $scan
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>.)
143 =cut
145 sub search_compat {
146 my (
147 $self, $query, $simple_query, $sort_by,
148 $servers, $results_per_page, $offset, $branches,
149 $item_types, $query_type, $scan
150 ) = @_;
152 if ( $scan ) {
153 return $self->_aggregation_scan( $query, $results_per_page, $offset );
156 my %options;
157 if ( !defined $offset or $offset < 0 ) {
158 $offset = 0;
160 $options{offset} = $offset;
161 my $results = $self->search($query, undef, $results_per_page, %options);
163 # Convert each result into a MARC::Record
164 my @records;
165 # opac-search expects results to be put in the
166 # right place in the array, according to $offset
167 my $index = $offset;
168 my $hits = $results->{'hits'};
169 foreach my $es_record (@{$hits->{'hits'}}) {
170 $records[$index++] = $self->decode_record_from_result($es_record->{'_source'});
173 # consumers of this expect a name-spaced result, we provide the default
174 # configuration.
175 my %result;
176 $result{biblioserver}{hits} = $hits->{'total'};
177 $result{biblioserver}{RECORDS} = \@records;
178 return (undef, \%result, $self->_convert_facets($results->{aggregations}));
181 =head2 search_auth_compat
183 my ( $results, $total ) =
184 $searcher->search_auth_compat( $query, $offset, $count, $skipmetadata, %options );
186 This has a similar calling convention to L<search>, however it returns its
187 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
189 =cut
191 sub search_auth_compat {
192 my ($self, $query, $offset, $count, $skipmetadata, %options) = @_;
194 if ( !defined $offset or $offset <= 0 ) {
195 $offset = 1;
197 # Uh, authority search uses 1-based offset..
198 $options{offset} = $offset - 1;
199 my $database = Koha::Database->new();
200 my $schema = $database->schema();
201 my $res = $self->search($query, undef, $count, %options);
203 my $bib_searcher = Koha::SearchEngine::Elasticsearch::Search->new({index => 'biblios'});
204 my @records;
205 my $hits = $res->{'hits'};
206 foreach my $es_record (@{$hits->{'hits'}}) {
207 my $record = $es_record->{'_source'};
208 my %result;
210 # I wonder if these should be real values defined in the mapping
211 # rather than hard-coded conversions.
212 #my $record = $_[0];
213 # Handle legacy nested arrays indexed with splitting enabled.
214 my $authid = $record->{ 'local-number' }[0];
215 $authid = @$authid[0] if (ref $authid eq 'ARRAY');
217 $result{authid} = $authid;
219 if (!defined $skipmetadata || !$skipmetadata) {
220 # TODO put all this info into the record at index time so we
221 # don't have to go and sort it all out now.
222 my $authtypecode = $record->{authtype};
223 my $rs = $schema->resultset('AuthType')
224 ->search( { authtypecode => $authtypecode } );
226 # FIXME there's an assumption here that we will get a result.
227 # the original code also makes an assumption that some provided
228 # authtypecode may sometimes be used instead of the one stored
229 # with the record. It's not documented why this is the case, so
230 # it's not reproduced here yet.
231 my $authtype = $rs->single;
232 my $auth_tag_to_report = $authtype ? $authtype->auth_tag_to_report : "";
233 my $marc = $self->decode_record_from_result($record);
234 my $mainentry = $marc->field($auth_tag_to_report);
235 my $reported_tag;
236 if ($mainentry) {
237 foreach ( $mainentry->subfields() ) {
238 $reported_tag .= '$' . $_->[0] . $_->[1];
241 # Turn the resultset into a hash
242 $result{authtype} = $authtype ? $authtype->authtypetext : $authtypecode;
243 $result{reported_tag} = $reported_tag;
245 # Reimplementing BuildSummary is out of scope because it'll be hard
246 $result{summary} =
247 C4::AuthoritiesMarc::BuildSummary( $marc, $result{authid},
248 $authtypecode );
249 $result{used} = $self->count_auth_use($bib_searcher, $authid);
251 push @records, \%result;
253 return ( \@records, $hits->{'total'} );
256 =head2 count_auth_use
258 my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
260 This runs a search to determine the number of records that reference the
261 specified authid. C<$bib_searcher> must be something compatible with
262 elasticsearch, as the query is built in this function.
264 =cut
266 sub count_auth_use {
267 my ($self, $bib_searcher, $authid) = @_;
269 my $query = {
270 query => {
271 bool => {
272 # query => { match_all => {} },
273 filter => { term => { 'koha-auth-number' => $authid } }
277 $bib_searcher->count($query);
280 =head2 simple_search_compat
282 my ( $error, $marcresults, $total_hits ) =
283 $searcher->simple_search( $query, $offset, $max_results, %options );
285 This is a simpler interface to the searching, intended to be similar enough to
286 L<C4::Search::SimpleSearch>.
288 Arguments:
290 =over 4
292 =item C<$query>
294 A thing to search for. It could be a simple string, or something constructed
295 with the appropriate QueryBuilder module.
297 =item C<$offset>
299 How many results to skip from the start of the results.
301 =item C<$max_results>
303 The max number of results to return. The default is 100 (because unlimited
304 is a pretty terrible thing to do.)
306 =item C<%options>
308 These options are unused by Elasticsearch
310 =back
312 Returns:
314 =over 4
316 =item C<$error>
318 if something went wrong, this'll contain some kind of error
319 message.
321 =item C<$marcresults>
323 an arrayref of MARC::Records (note that this is different from the
324 L<C4::Search> version which will return plain XML, but too bad.)
326 =item C<$total_hits>
328 the total number of results that this search could have returned.
330 =back
332 =cut
334 sub simple_search_compat {
335 my ($self, $query, $offset, $max_results) = @_;
337 return ('No query entered', undef, undef) unless $query;
339 my %options;
340 $offset = 0 if not defined $offset or $offset < 0;
341 $options{offset} = $offset;
342 $max_results //= 100;
344 unless (ref $query) {
345 # We'll push it through the query builder to sanitise everything.
346 my $qb = Koha::SearchEngine::QueryBuilder->new({index => $self->index});
347 (undef,$query) = $qb->build_query_compat(undef, [$query]);
349 my $results = $self->search($query, undef, $max_results, %options);
350 my @records;
351 my $hits = $results->{'hits'};
352 foreach my $es_record (@{$hits->{'hits'}}) {
353 push @records, $self->decode_record_from_result($es_record->{'_source'});
355 return (undef, \@records, $hits->{'total'});
358 =head2 extract_biblionumber
360 my $biblionumber = $searcher->extract_biblionumber( $searchresult );
362 $searchresult comes from simple_search_compat.
364 Returns the biblionumber from the search result record.
366 =cut
368 sub extract_biblionumber {
369 my ( $self, $searchresultrecord ) = @_;
370 return Koha::SearchEngine::Search::extract_biblionumber( $searchresultrecord );
373 =head2 decode_record_from_result
374 my $marc_record = $self->decode_record_from_result(@result);
376 Extracts marc data from Elasticsearch result and decodes to MARC::Record object
378 =cut
380 sub decode_record_from_result {
381 # Result is passed in as array, will get flattened
382 # and first element will be $result
383 my ( $self, $result ) = @_;
384 if ($result->{marc_format} eq 'base64ISO2709') {
385 return MARC::Record->new_from_usmarc(decode_base64($result->{marc_data}));
387 elsif ($result->{marc_format} eq 'MARCXML') {
388 return MARC::Record->new_from_xml($result->{marc_data}, 'UTF-8', uc C4::Context->preference('marcflavour'));
390 elsif ($result->{marc_format} eq 'ARRAY') {
391 return $self->_array_to_marc($result->{marc_data_array});
393 else {
394 Koha::Exceptions::Elasticsearch->throw("Missing marc_format field in Elasticsearch result");
398 =head2 max_result_window
400 Returns the maximum number of results that can be fetched
402 This directly requests Elasticsearch for the setting index.max_result_window (or
403 the default value for this setting in case it is not set)
405 =cut
407 sub max_result_window {
408 my ($self) = @_;
410 $self->store(
411 Catmandu::Store::ElasticSearch->new(%{ $self->get_elasticsearch_params })
412 ) unless $self->store;
414 my $index_name = $self->store->index_name;
415 my $settings = $self->store->es->indices->get_settings(
416 index => $index_name,
417 params => { include_defaults => 'true', flat_settings => 'true' },
420 my $max_result_window = $settings->{$index_name}->{settings}->{'index.max_result_window'};
421 $max_result_window //= $settings->{$index_name}->{defaults}->{'index.max_result_window'};
423 return $max_result_window;
426 =head2 _convert_facets
428 my $koha_facets = _convert_facets($es_facets);
430 Converts elasticsearch facets types to the form that Koha expects.
431 It expects the ES facet name to match the Koha type, for example C<itype>,
432 C<au>, C<su-to>, etc.
434 =cut
436 sub _convert_facets {
437 my ( $self, $es, $exp_facet ) = @_;
439 return if !$es;
441 # These should correspond to the ES field names, as opposed to the CCL
442 # things that zebra uses.
443 my %type_to_label;
444 my %label = (
445 author => 'Authors',
446 itype => 'ItemTypes',
447 location => 'Location',
448 'su-geo' => 'Places',
449 'title-series' => 'Series',
450 subject => 'Topics',
451 ccode => 'CollectionCodes',
452 holdingbranch => 'HoldingLibrary',
453 homebranch => 'HomeLibrary',
454 ln => 'Language',
456 my @facetable_fields =
457 Koha::SearchEngine::Elasticsearch->get_facetable_fields;
458 for my $f (@facetable_fields) {
459 next unless defined $f->facet_order;
460 $type_to_label{ $f->name } =
461 { order => $f->facet_order, label => $label{ $f->name } };
464 # We also have some special cases, e.g. itypes that need to show the
465 # value rather than the code.
466 my @itypes = Koha::ItemTypes->search;
467 my @libraries = Koha::Libraries->search;
468 my $library_names = { map { $_->branchcode => $_->branchname } @libraries };
469 my @locations = Koha::AuthorisedValues->search( { category => 'LOC' } );
470 my $opac = C4::Context->interface eq 'opac' ;
471 my %special = (
472 itype => { map { $_->itemtype => $_->description } @itypes },
473 location => { map { $_->authorised_value => ( $opac ? ( $_->lib_opac || $_->lib ) : $_->lib ) } @locations },
474 holdingbranch => $library_names,
475 homebranch => $library_names
477 my @facets;
478 $exp_facet //= '';
479 while ( my ( $type, $data ) = each %$es ) {
480 next if !exists( $type_to_label{$type} );
482 # We restrict to the most popular $limit !results
483 my $limit = C4::Context->preference('FacetMaxCount');
484 my $facet = {
485 type_id => $type . '_id',
486 "type_label_$type_to_label{$type}{label}" => 1,
487 type_link_value => $type,
488 order => $type_to_label{$type}{order},
490 $limit = @{ $data->{buckets} } if ( $limit > @{ $data->{buckets} } );
491 foreach my $term ( @{ $data->{buckets} }[ 0 .. $limit - 1 ] ) {
492 my $t = $term->{key};
493 my $c = $term->{doc_count};
494 my $label;
495 if ( exists( $special{$type} ) ) {
496 $label = $special{$type}->{$t} // $t;
498 else {
499 $label = $t;
501 push @{ $facet->{facets} }, {
502 facet_count => $c,
503 facet_link_value => $t,
504 facet_title_value => $t . " ($c)",
505 facet_label_value => $label, # TODO either truncate this,
506 # or make the template do it like it should anyway
507 type_link_value => $type,
510 push @facets, $facet if exists $facet->{facets};
513 @facets = sort { $a->{order} <=> $b->{order} } @facets;
514 return \@facets;
517 =head2 _aggregation_scan
519 my $result = $self->_aggregration_scan($query, 10, 0);
521 Perform an aggregation request for scan purposes.
523 =cut
525 sub _aggregation_scan {
526 my ($self, $query, $results_per_page, $offset) = @_;
528 if (!scalar(keys %{$query->{aggregations}})) {
529 my %result = {
530 biblioserver => {
531 hits => 0,
532 RECORDS => undef
535 return (undef, \%result, undef);
537 my ($field) = keys %{$query->{aggregations}};
538 $query->{aggregations}{$field}{terms}{size} = 1000;
539 my $results = $self->search($query, 1, 0);
541 # Convert each result into a MARC::Record
542 my (@records, $index);
543 # opac-search expects results to be put in the
544 # right place in the array, according to $offset
545 $index = $offset - 1;
547 my $count = scalar(@{$results->{aggregations}{$field}{buckets}});
548 for (my $index = $offset; $index - $offset < $results_per_page && $index < $count; $index++) {
549 my $bucket = $results->{aggregations}{$field}{buckets}->[$index];
550 # Scan values are expressed as:
551 # - MARC21: 100a (count) and 245a (term)
552 # - UNIMARC: 200f (count) and 200a (term)
553 my $marc = MARC::Record->new;
554 $marc->encoding('UTF-8');
555 if (C4::Context->preference('marcflavour') eq 'UNIMARC') {
556 $marc->append_fields(
557 MARC::Field->new((200, ' ', ' ', 'f' => $bucket->{doc_count}))
559 $marc->append_fields(
560 MARC::Field->new((200, ' ', ' ', 'a' => $bucket->{key}))
562 } else {
563 $marc->append_fields(
564 MARC::Field->new((100, ' ', ' ', 'a' => $bucket->{doc_count}))
566 $marc->append_fields(
567 MARC::Field->new((245, ' ', ' ', 'a' => $bucket->{key}))
570 $records[$index] = $marc->as_usmarc();
572 # consumers of this expect a namespaced result, we provide the default
573 # configuration.
574 my %result;
575 $result{biblioserver}{hits} = $count;
576 $result{biblioserver}{RECORDS} = \@records;
577 return (undef, \%result, undef);