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);
42 use Catmandu::Store::ElasticSearch;
44 use Data::Dumper; #TODO remove
47 Koha::SearchEngine::Elasticsearch::Search->mk_accessors(qw( store ));
51 my $results = $searcher->search($query, $page, $count, %options);
53 Run a search using the query. It'll return C<$count> results, starting at page
54 C<$page> (C<$page> counts from 1, anything less that, or C<undef> becomes 1.)
55 C<$count> is also the number of entries on a page.
57 C<%options> is a hash containing extra options:
63 If provided, this overrides the C<$page> value, and specifies the record as
64 an offset (i.e. the number of the record to start with), rather than a page.
73 my ($self, $query, $page, $count, %options) = @_;
75 my $params = $self->get_elasticsearch_params();
77 # 20 is the default number of results per page
78 $paging{limit} = $count || 20;
79 # ES/Catmandu doesn't want pages, it wants a record to start from.
80 if (exists $options{offset}) {
81 $paging{start} = $options{offset};
83 $page = (!defined($page) || ($page <= 0)) ? 0 : $page - 1;
84 $paging{start} = $page * $paging{limit};
87 Catmandu::Store::ElasticSearch->new(
88 %$params, trace_calls => 1,
90 ) unless $self->store;
91 my $results = $self->store->bag->search( %$query, %paging );
97 my $count = $searcher->count($query);
99 This mimics a search request, but just gets the result count instead. That's
100 faster than pulling all the data in, ususally.
105 my ( $self, $query ) = @_;
107 my $params = $self->get_elasticsearch_params();
109 Catmandu::Store::ElasticSearch->new( %$params, trace_calls => 0, ) )
112 my $searcher = $self->store->bag->searcher(query => $query);
113 my $count = $searcher->count();
119 my ( $error, $results, $facets ) = $search->search_compat(
120 $query, $simple_query, \@sort_by, \@servers,
121 $results_per_page, $offset, $expanded_facet, $branches,
125 A search interface somewhat compatible with L<C4::Search->getRecords>. Anything
126 that is returned in the query created by build_query_compat will probably
127 get ignored here, along with some other things (like C<@servers>.)
133 $self, $query, $simple_query, $sort_by,
134 $servers, $results_per_page, $offset, $expanded_facet,
135 $branches, $query_type, $scan
139 $options{offset} = $offset;
140 my $results = $self->search($query, undef, $results_per_page, %options);
142 # Convert each result into a MARC::Record
143 my (@records, $index);
144 $index = $offset; # opac-search expects results to be put in the
145 # right place in the array, according to $offset
147 # The results come in an array for some reason
148 my $marc_json = @_[0]->{record};
149 my $marc = $self->json2marc($marc_json);
150 $records[$index++] = $marc;
152 # consumers of this expect a name-spaced result, we provide the default
155 $result{biblioserver}{hits} = $results->total;
156 $result{biblioserver}{RECORDS} = \@records;
157 return (undef, \%result, $self->_convert_facets($results->{facets}));
160 =head2 search_auth_compat
162 my ( $results, $total ) =
163 $searcher->search_auth_compat( $query, $page, $count, %options );
165 This has a similar calling convention to L<search>, however it returns its
166 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
170 sub search_auth_compat {
174 my $database = Koha::Database->new();
175 my $schema = $database->schema();
176 my $res = $self->search(@_);
177 my $bib_searcher = Koha::SearchEngine::Elasticsearch::Search->new({index => 'biblios'});
183 my $marc_json = $record->{record};
185 # I wonder if these should be real values defined in the mapping
186 # rather than hard-coded conversions.
187 # Our results often come through as nested arrays, to fix this
188 # requires changes in catmandu.
189 my $authid = $record->{ 'local-number' }[0][0];
190 $result{authid} = $authid;
192 # TODO put all this info into the record at index time so we
193 # don't have to go and sort it all out now.
194 my $authtypecode = $record->{authtype};
195 my $rs = $schema->resultset('AuthType')
196 ->search( { authtypecode => $authtypecode } );
198 # FIXME there's an assumption here that we will get a result.
199 # the original code also makes an assumption that some provided
200 # authtypecode may sometimes be used instead of the one stored
201 # with the record. It's not documented why this is the case, so
202 # it's not reproduced here yet.
203 my $authtype = $rs->single;
204 my $auth_tag_to_report = $authtype->auth_tag_to_report;
205 my $marc = $self->json2marc($marc_json);
206 my $mainentry = $marc->field($auth_tag_to_report);
209 foreach ( $mainentry->subfields() ) {
210 $reported_tag .= '$' . $_->[0] . $_->[1];
213 # Turn the resultset into a hash
215 foreach my $col ($authtype->result_source->columns) {
216 $authtype_cols{$col} = $authtype->get_column($col);
218 $result{authtype} = $authtype->authtypetext;
219 $result{reported_tag} = $reported_tag;
221 # Reimplementing BuildSummary is out of scope because it'll be hard
223 C4::AuthoritiesMarc::BuildSummary( $marc, $result{authid},
225 $result{used} = $self->count_auth_use($bib_searcher, $authid);
226 push @records, \%result;
229 return ( \@records, $res->total );
232 =head2 count_auth_use
234 my $count = $auth_searcher->count_auth_use($bib_searcher, $authid);
236 This runs a search to determine the number of records that reference the
237 specified authid. C<$bib_searcher> must be something compatible with
238 elasticsearch, as the query is built in this function.
243 my ($self, $bib_searcher, $authid) = @_;
248 query => { match_all => {} },
249 filter => { term => { an => $authid } }
253 $bib_searcher->count($query);
260 my $marc = $self->json2marc($marc_json);
262 Converts the form of marc (based on its JSON, but as a Perl structure) that
263 Catmandu stores into a MARC::Record object.
268 my ( $self, $marcjson ) = @_;
270 my $marc = MARC::Record->new();
271 $marc->encoding('UTF-8');
274 # [ '245', '1', '2', 'a' => 'Title', 'b' => 'Subtitle' ]
275 # conveniently, this is the form that MARC::Field->new() likes
276 foreach $field (@$marcjson) {
277 next if @$field < 5; # Shouldn't be possible, but...
278 if ( $field->[0] eq 'LDR' ) {
279 $marc->leader( $field->[4] );
282 my $marc_field = MARC::Field->new(@$field);
283 $marc->append_fields($marc_field);
289 =head2 _convert_facets
291 my $koha_facets = _convert_facets($es_facets);
293 Converts elasticsearch facets types to the form that Koha expects.
294 It expects the ES facet name to match the Koha type, for example C<itype>,
295 C<au>, C<su-to>, etc.
299 sub _convert_facets {
300 my ( $self, $es ) = @_;
302 return undef if !$es;
304 # These should correspond to the ES field names, as opposed to the CCL
305 # things that zebra uses.
306 my %type_to_label = (
308 location => 'Location',
309 itype => 'ItemTypes',
312 'su-geo' => 'Places',
315 # We also have some special cases, e.g. itypes that need to show the
316 # value rather than the code.
317 my $itypes = Koha::ItemTypes->new();
318 my %special = ( itype => sub { $itypes->get_description_for_code(@_) }, );
320 while ( ( $type, $data ) = each %$es ) {
321 next if !exists( $type_to_label{$type} );
323 type_id => $type . '_id',
325 expandable => 1, # TODO figure how that's supposed to work
326 "type_label_$type_to_label{$type}" => 1,
327 type_link_value => $type,
329 foreach my $term ( @{ $data->{terms} } ) {
330 my $t = $term->{term};
331 my $c = $term->{count};
332 if ( exists( $special{$type} ) ) {
333 $label = $special{$type}->($t);
338 push @{ $facet->{facets} }, {
340 facet_link_value => $t,
341 facet_title_value => $t . " ($c)",
342 facet_label_value => $label, # TODO either truncate this,
343 # or make the template do it like it should anyway
344 type_link_value => $type,
347 push @res, $facet if exists $facet->{facets};