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
26 my $searcher = Koha::SearchEngine::ElasticSearch::Search->new();
27 my $builder = Koha::SearchEngine::Elasticsearch::QueryBuilder->new();
28 my $query = $builder->build_query('perl');
29 my $results = $searcher->search($query);
30 print "There were " . $results->total . " results.\n";
39 use base qw(Koha::ElasticSearch);
41 use Koha::SearchEngine::QueryBuilder;
43 use Catmandu::Store::ElasticSearch;
45 use Data::Dumper; #TODO remove
48 Koha::SearchEngine::Elasticsearch::Search->mk_accessors(qw( store ));
52 my $results = $searcher->search($query, $page, $count, %options);
54 Run a search using the query. It'll return C<$count> results, starting at page
55 C<$page> (C<$page> counts from 1, anything less that, or C<undef> becomes 1.)
56 C<$count> is also the number of entries on a page.
58 C<%options> is a hash containing extra options:
64 If provided, this overrides the C<$page> value, and specifies the record as
65 an offset (i.e. the number of the record to start with), rather than a page.
74 my ($self, $query, $page, $count, %options) = @_;
76 my $params = $self->get_elasticsearch_params();
78 # 20 is the default number of results per page
79 $paging{limit} = $count || 20;
80 # ES/Catmandu doesn't want pages, it wants a record to start from.
81 if (exists $options{offset}) {
82 $paging{start} = $options{offset};
84 $page = (!defined($page) || ($page <= 0)) ? 0 : $page - 1;
85 $paging{start} = $page * $paging{limit};
88 Catmandu::Store::ElasticSearch->new(
89 %$params, trace_calls => 1,
91 ) unless $self->store;
92 my $results = $self->store->bag->search( %$query, %paging );
98 my $count = $searcher->count($query);
100 This mimics a search request, but just gets the result count instead. That's
101 faster than pulling all the data in, ususally.
106 my ( $self, $query ) = @_;
108 my $params = $self->get_elasticsearch_params();
110 Catmandu::Store::ElasticSearch->new( %$params, trace_calls => 0, ) )
113 my $searcher = $self->store->bag->searcher(query => $query);
114 my $count = $searcher->count();
120 my ( $error, $results, $facets ) = $search->search_compat(
121 $query, $simple_query, \@sort_by, \@servers,
122 $results_per_page, $offset, $expanded_facet, $branches,
126 A search interface somewhat compatible with L<C4::Search->getRecords>. Anything
127 that is returned in the query created by build_query_compat will probably
128 get ignored here, along with some other things (like C<@servers>.)
134 $self, $query, $simple_query, $sort_by,
135 $servers, $results_per_page, $offset, $expanded_facet,
136 $branches, $query_type, $scan
140 $options{offset} = $offset;
141 my $results = $self->search($query, undef, $results_per_page, %options);
143 # Convert each result into a MARC::Record
144 my (@records, $index);
145 $index = $offset; # opac-search expects results to be put in the
146 # right place in the array, according to $offset
148 # The results come in an array for some reason
149 my $marc_json = @_[0]->{record};
150 my $marc = $self->json2marc($marc_json);
151 $records[$index++] = $marc;
153 # consumers of this expect a name-spaced result, we provide the default
156 $result{biblioserver}{hits} = $results->total;
157 $result{biblioserver}{RECORDS} = \@records;
158 return (undef, \%result, $self->_convert_facets($results->{facets}));
161 =head2 search_auth_compat
163 my ( $results, $total ) =
164 $searcher->search_auth_compat( $query, $page, $count, %options );
166 This has a similar calling convention to L<search>, however it returns its
167 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
171 sub search_auth_compat {
175 my $database = Koha::Database->new();
176 my $schema = $database->schema();
177 my $res = $self->search(@_);
178 my $bib_searcher = Koha::SearchEngine::Elasticsearch::Search->new({index => 'biblios'});
184 my $marc_json = $record->{record};
186 # I wonder if these should be real values defined in the mapping
187 # rather than hard-coded conversions.
188 # Our results often come through as nested arrays, to fix this
189 # requires changes in catmandu.
190 my $authid = $record->{ 'Local-number' }[0][0];
191 $result{authid} = $authid;
193 # TODO put all this info into the record at index time so we
194 # don't have to go and sort it all out now.
195 my $authtypecode = $record->{authtype};
196 my $rs = $schema->resultset('AuthType')
197 ->search( { authtypecode => $authtypecode } );
199 # FIXME there's an assumption here that we will get a result.
200 # the original code also makes an assumption that some provided
201 # authtypecode may sometimes be used instead of the one stored
202 # with the record. It's not documented why this is the case, so
203 # it's not reproduced here yet.
204 my $authtype = $rs->single;
205 my $auth_tag_to_report = $authtype->auth_tag_to_report;
206 my $marc = $self->json2marc($marc_json);
207 my $mainentry = $marc->field($auth_tag_to_report);
210 foreach ( $mainentry->subfields() ) {
211 $reported_tag .= '$' . $_->[0] . $_->[1];
214 # Turn the resultset into a hash
216 foreach my $col ($authtype->result_source->columns) {
217 $authtype_cols{$col} = $authtype->get_column($col);
219 $result{authtype} = $authtype->authtypetext;
220 $result{reported_tag} = $reported_tag;
222 # Reimplementing BuildSummary is out of scope because it'll be hard
224 C4::AuthoritiesMarc::BuildSummary( $marc, $result{authid},
226 $result{used} = $self->count_auth_use($bib_searcher, $authid);
227 push @records, \%result;
230 return ( \@records, $res->total );
233 =head2 count_auth_use
235 my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
237 This runs a search to determine the number of records that reference the
238 specified authid. C<$bib_searcher> must be something compatible with
239 elasticsearch, as the query is built in this function.
244 my ($self, $bib_searcher, $authid) = @_;
249 query => { match_all => {} },
250 filter => { term => { an => $authid } }
254 $bib_searcher->count($query);
257 =head2 simple_search_compat
259 my ( $error, $marcresults, $total_hits ) =
260 $searcher->simple_search( $query, $offset, $max_results );
262 This is a simpler interface to the searching, intended to be similar enough to
263 L<C4::Search::SimpleSearch>.
271 A thing to search for. It could be a simple string, or something constructed
272 with the appropriate QueryBuilder module.
276 How many results to skip from the start of the results.
278 =item C<$max_results>
280 The max number of results to return. The default is 100 (because unlimited
281 is a pretty terrible thing to do.)
291 if something went wrong, this'll contain some kind of error
294 =item C<$marcresults>
296 an arrayref of MARC::Records (note that this is different from the
297 L<C4::Search> version which will return plain XML, but too bad.)
301 the total number of results that this search could have returned.
307 sub simple_search_compat {
308 my ($self, $query, $offset, $max_results) = @_;
310 return ('No query entered', undef, undef) unless $query;
313 $options{offset} = $offset // 0;
314 $max_results //= 100;
316 unless (ref $query) {
317 # We'll push it through the query builder to sanitise everything.
318 my $qb = Koha::SearchEngine::QueryBuilder->new();
319 (undef,$query) = $qb->build_query_compat(undef, [$query]);
321 my $results = $self->search($query, undef, $max_results, %options);
324 # The results come in an array for some reason
325 my $marc_json = @_[0]->{record};
326 my $marc = $self->json2marc($marc_json);
327 push @records, $marc;
329 return (undef, \@records, $results->total);
334 my $marc = $self->json2marc($marc_json);
336 Converts the form of marc (based on its JSON, but as a Perl structure) that
337 Catmandu stores into a MARC::Record object.
342 my ( $self, $marcjson ) = @_;
344 my $marc = MARC::Record->new();
345 $marc->encoding('UTF-8');
348 # [ '245', '1', '2', 'a' => 'Title', 'b' => 'Subtitle' ]
349 # conveniently, this is the form that MARC::Field->new() likes
350 foreach $field (@$marcjson) {
351 next if @$field < 5; # Shouldn't be possible, but...
352 if ( $field->[0] eq 'LDR' ) {
353 $marc->leader( $field->[4] );
356 my $marc_field = MARC::Field->new(@$field);
357 $marc->append_fields($marc_field);
363 =head2 _convert_facets
365 my $koha_facets = _convert_facets($es_facets);
367 Converts elasticsearch facets types to the form that Koha expects.
368 It expects the ES facet name to match the Koha type, for example C<itype>,
369 C<au>, C<su-to>, etc.
373 sub _convert_facets {
374 my ( $self, $es ) = @_;
376 return undef if !$es;
378 # These should correspond to the ES field names, as opposed to the CCL
379 # things that zebra uses.
380 my %type_to_label = (
382 location => 'Location',
383 itype => 'ItemTypes',
386 'su-geo' => 'Places',
389 # We also have some special cases, e.g. itypes that need to show the
390 # value rather than the code.
391 my $itypes = Koha::ItemTypes->new();
392 my %special = ( itype => sub { $itypes->get_description_for_code(@_) }, );
394 while ( ( $type, $data ) = each %$es ) {
395 next if !exists( $type_to_label{$type} );
397 type_id => $type . '_id',
399 expandable => 1, # TODO figure how that's supposed to work
400 "type_label_$type_to_label{$type}" => 1,
401 type_link_value => $type,
403 foreach my $term ( @{ $data->{terms} } ) {
404 my $t = $term->{term};
405 my $c = $term->{count};
406 if ( exists( $special{$type} ) ) {
407 $label = $special{$type}->($t);
412 push @{ $facet->{facets} }, {
414 facet_link_value => $t,
415 facet_title_value => $t . " ($c)",
416 facet_label_value => $label, # TODO either truncate this,
417 # or make the template do it like it should anyway
418 type_link_value => $type,
421 push @res, $facet if exists $facet->{facets};