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);
46 use Koha
::AuthorisedValues
;
47 use Koha
::SearchEngine
::QueryBuilder
;
49 use Catmandu
::Store
::ElasticSearch
;
51 use Data
::Dumper
; #TODO remove
54 Koha
::SearchEngine
::Elasticsearch
::Search
->mk_accessors(qw( store ));
58 my $results = $searcher->search($query, $page, $count, %options);
60 Run a search using the query. It'll return C<$count> results, starting at page
61 C<$page> (C<$page> counts from 1, anything less that, or C<undef> becomes 1.)
62 C<$count> is also the number of entries on a page.
64 C<%options> is a hash containing extra options:
70 If provided, this overrides the C<$page> value, and specifies the record as
71 an offset (i.e. the number of the record to start with), rather than a page.
80 my ($self, $query, $page, $count, %options) = @_;
82 my $params = $self->get_elasticsearch_params();
84 # 20 is the default number of results per page
85 $paging{limit
} = $count || 20;
86 # ES/Catmandu doesn't want pages, it wants a record to start from.
87 if (exists $options{offset
}) {
88 $paging{start
} = $options{offset
};
90 $page = (!defined($page) || ($page <= 0)) ?
0 : $page - 1;
91 $paging{start
} = $page * $paging{limit
};
94 Catmandu
::Store
::ElasticSearch
->new(
97 ) unless $self->store;
99 $self->store->bag->search( %$query, %paging );
102 die $self->process_error($@
);
109 my $count = $searcher->count($query);
111 This mimics a search request, but just gets the result count instead. That's
112 faster than pulling all the data in, usually.
117 my ( $self, $query ) = @_;
119 my $params = $self->get_elasticsearch_params();
121 Catmandu
::Store
::ElasticSearch
->new( %$params, trace_calls
=> 0, ) )
124 my $search = $self->store->bag->search( %$query);
125 my $count = $search->total() || 0;
131 my ( $error, $results, $facets ) = $search->search_compat(
132 $query, $simple_query, \@sort_by, \@servers,
133 $results_per_page, $offset, $expanded_facet, $branches,
137 A search interface somewhat compatible with L<C4::Search->getRecords>. Anything
138 that is returned in the query created by build_query_compat will probably
139 get ignored here, along with some other things (like C<@servers>.)
145 $self, $query, $simple_query, $sort_by,
146 $servers, $results_per_page, $offset, $expanded_facet,
147 $branches, $query_type, $scan
150 $options{offset
} = $offset;
151 $options{expanded_facet
} = $expanded_facet;
152 my $results = $self->search($query, undef, $results_per_page, %options);
154 # Convert each result into a MARC::Record
155 my (@records, $index);
156 $index = $offset; # opac-search expects results to be put in the
157 # right place in the array, according to $offset
159 # The results come in an array for some reason
160 my $marc_json = $_[0]->{record
};
161 my $marc = $self->json2marc($marc_json);
162 $records[$index++] = $marc;
164 # consumers of this expect a name-spaced result, we provide the default
167 $result{biblioserver
}{hits
} = $results->total;
168 $result{biblioserver
}{RECORDS
} = \
@records;
169 return (undef, \
%result, $self->_convert_facets($results->{aggregations
}, $expanded_facet));
172 =head2 search_auth_compat
174 my ( $results, $total ) =
175 $searcher->search_auth_compat( $query, $page, $count, %options );
177 This has a similar calling convention to L<search>, however it returns its
178 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
182 sub search_auth_compat
{
186 my $database = Koha
::Database
->new();
187 my $schema = $database->schema();
188 my $res = $self->search(@_);
189 my $bib_searcher = Koha
::SearchEngine
::Elasticsearch
::Search
->new({index => 'biblios'});
195 my $marc_json = $record->{record
};
197 # I wonder if these should be real values defined in the mapping
198 # rather than hard-coded conversions.
199 # Our results often come through as nested arrays, to fix this
200 # requires changes in catmandu.
201 my $authid = $record->{ 'Local-number' }[0][0];
202 $result{authid
} = $authid;
204 # TODO put all this info into the record at index time so we
205 # don't have to go and sort it all out now.
206 my $authtypecode = $record->{authtype
};
207 my $rs = $schema->resultset('AuthType')
208 ->search( { authtypecode
=> $authtypecode } );
210 # FIXME there's an assumption here that we will get a result.
211 # the original code also makes an assumption that some provided
212 # authtypecode may sometimes be used instead of the one stored
213 # with the record. It's not documented why this is the case, so
214 # it's not reproduced here yet.
215 my $authtype = $rs->single;
216 my $auth_tag_to_report = $authtype->auth_tag_to_report;
217 my $marc = $self->json2marc($marc_json);
218 my $mainentry = $marc->field($auth_tag_to_report);
221 foreach ( $mainentry->subfields() ) {
222 $reported_tag .= '$' . $_->[0] . $_->[1];
225 # Turn the resultset into a hash
227 foreach my $col ($authtype->result_source->columns) {
228 $authtype_cols{$col} = $authtype->get_column($col);
230 $result{authtype
} = $authtype->authtypetext;
231 $result{reported_tag
} = $reported_tag;
233 # Reimplementing BuildSummary is out of scope because it'll be hard
235 C4
::AuthoritiesMarc
::BuildSummary
( $marc, $result{authid
},
237 $result{used
} = $self->count_auth_use($bib_searcher, $authid);
238 push @records, \
%result;
241 return ( \
@records, $res->total );
244 =head2 count_auth_use
246 my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
248 This runs a search to determine the number of records that reference the
249 specified authid. C<$bib_searcher> must be something compatible with
250 elasticsearch, as the query is built in this function.
255 my ($self, $bib_searcher, $authid) = @_;
260 # query => { match_all => {} },
261 filter
=> { term
=> { an
=> $authid } }
265 $bib_searcher->count($query);
268 =head2 simple_search_compat
270 my ( $error, $marcresults, $total_hits ) =
271 $searcher->simple_search( $query, $offset, $max_results, %options );
273 This is a simpler interface to the searching, intended to be similar enough to
274 L<C4::Search::SimpleSearch>.
282 A thing to search for. It could be a simple string, or something constructed
283 with the appropriate QueryBuilder module.
287 How many results to skip from the start of the results.
289 =item C<$max_results>
291 The max number of results to return. The default is 100 (because unlimited
292 is a pretty terrible thing to do.)
296 These options are unused by Elasticsearch
306 if something went wrong, this'll contain some kind of error
309 =item C<$marcresults>
311 an arrayref of MARC::Records (note that this is different from the
312 L<C4::Search> version which will return plain XML, but too bad.)
316 the total number of results that this search could have returned.
322 sub simple_search_compat
{
323 my ($self, $query, $offset, $max_results) = @_;
325 return ('No query entered', undef, undef) unless $query;
328 $options{offset
} = $offset // 0;
329 $max_results //= 100;
331 unless (ref $query) {
332 # We'll push it through the query builder to sanitise everything.
333 my $qb = Koha
::SearchEngine
::QueryBuilder
->new({index => $self->index});
334 (undef,$query) = $qb->build_query_compat(undef, [$query]);
336 my $results = $self->search($query, undef, $max_results, %options);
339 # The results come in an array for some reason
340 my $marc_json = $_[0]->{record
};
341 my $marc = $self->json2marc($marc_json);
342 push @records, $marc;
344 return (undef, \
@records, $results->total);
349 my $marc = $self->json2marc($marc_json);
351 Converts the form of marc (based on its JSON, but as a Perl structure) that
352 Catmandu stores into a MARC::Record object.
357 my ( $self, $marcjson ) = @_;
359 my $marc = MARC
::Record
->new();
360 $marc->encoding('UTF-8');
363 # [ '245', '1', '2', 'a' => 'Title', 'b' => 'Subtitle' ]
365 # [ '001', undef, undef, '_', 'a value' ]
366 # conveniently, this is the form that MARC::Field->new() likes
367 foreach my $field (@
$marcjson) {
369 if ( $field->[0] eq 'LDR' ) {
370 $marc->leader( $field->[4] );
373 my $tag = $field->[0];
375 if ( MARC
::Field
->is_controlfield_tag( $field->[0] ) ) {
376 $marc_field = MARC
::Field
->new($field->[0], $field->[4]);
378 $marc_field = MARC
::Field
->new(@
$field);
380 $marc->append_fields($marc_field);
386 =head2 _convert_facets
388 my $koha_facets = _convert_facets($es_facets, $expanded_facet);
390 Converts elasticsearch facets types to the form that Koha expects.
391 It expects the ES facet name to match the Koha type, for example C<itype>,
392 C<au>, C<su-to>, etc.
394 C<$expanded_facet> is the facet that we want to show FacetMaxCount entries for, rather
395 than just 5 like normal.
399 sub _convert_facets
{
400 my ( $self, $es, $exp_facet ) = @_;
404 # These should correspond to the ES field names, as opposed to the CCL
405 # things that zebra uses.
406 # TODO let the library define the order using the interface.
407 my %type_to_label = (
408 author
=> { order
=> 1, label
=> 'Authors', },
409 itype
=> { order
=> 2, label
=> 'ItemTypes', },
410 location
=> { order
=> 3, label
=> 'Location', },
411 'su-geo' => { order
=> 4, label
=> 'Places', },
412 se
=> { order
=> 5, label
=> 'Series', },
413 subject
=> { order
=> 6, label
=> 'Topics', },
414 ccode
=> { order
=> 7, label
=> 'CollectionCodes',},
415 holdingbranch
=> { order
=> 8, label
=> 'HoldingLibrary' },
416 homebranch
=> { order
=> 9, label
=> 'HomeLibrary' }
419 # We also have some special cases, e.g. itypes that need to show the
420 # value rather than the code.
421 my @itypes = Koha
::ItemTypes
->search;
422 my @libraries = Koha
::Libraries
->search;
423 my $library_names = { map { $_->branchcode => $_->branchname } @libraries };
424 my @locations = Koha
::AuthorisedValues
->search( { category
=> 'LOC' } );
425 my $opac = C4
::Context
->interface eq 'opac' ;
427 itype
=> { map { $_->itemtype => $_->description } @itypes },
428 location
=> { map { $_->authorised_value => ( $opac ?
( $_->lib_opac || $_->lib ) : $_->lib ) } @locations },
429 holdingbranch
=> $library_names,
430 homebranch
=> $library_names
434 while ( my ( $type, $data ) = each %$es ) {
435 next if !exists( $type_to_label{$type} );
437 # We restrict to the most popular $limit !results
438 my $limit = ( $type eq $exp_facet ) ? C4
::Context
->preference('FacetMaxCount') : 5;
440 type_id
=> $type . '_id',
442 expandable
=> ( $type ne $exp_facet )
443 && ( @
{ $data->{buckets
} } > $limit ),
444 "type_label_$type_to_label{$type}{label}" => 1,
445 type_link_value
=> $type,
446 order
=> $type_to_label{$type}{order
},
448 $limit = @
{ $data->{buckets
} } if ( $limit > @
{ $data->{buckets
} } );
449 foreach my $term ( @
{ $data->{buckets
} }[ 0 .. $limit - 1 ] ) {
450 my $t = $term->{key
};
451 my $c = $term->{doc_count
};
453 if ( exists( $special{$type} ) ) {
454 $label = $special{$type}->{$t} // $t;
459 push @
{ $facet->{facets
} }, {
461 facet_link_value
=> $t,
462 facet_title_value
=> $t . " ($c)",
463 facet_label_value
=> $label, # TODO either truncate this,
464 # or make the template do it like it should anyway
465 type_link_value
=> $type,
468 push @facets, $facet if exists $facet->{facets
};
471 @facets = sort { $a->{order
} cmp $b->{order
} } @facets;