Bug 12478: more authorities
[koha.git] / Koha / SearchEngine / Elasticsearch / Search.pm
1 package Koha::SearchEngine::Elasticsearch::Search;
2
3 # Copyright 2014 Catalyst IT
4 #
5 # This file is part of Koha.
6 #
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
10 # version.
11 #
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.
15 #
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.
19
20 =head1 NAME
21
22 Koha::SearchEngine::ElasticSearch::Search - search functions for Elasticsearch
23
24 =head1 SYNOPSIS
25
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";
31     $results->each(sub {
32         push @hits, @_[0];
33     });
34
35 =head1 METHODS
36
37 =cut
38
39 use base qw(Koha::ElasticSearch);
40 use Koha::ItemTypes;
41
42 use Catmandu::Store::ElasticSearch;
43
44 use Data::Dumper; #TODO remove
45 use Carp qw(cluck);
46
47 Koha::SearchEngine::Elasticsearch::Search->mk_accessors(qw( store ));
48
49 =head2 search
50
51     my $results = $searcher->search($query, $page, $count, %options);
52
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.
56
57 C<%options> is a hash containing extra options:
58
59 =over 4
60
61 =item offset
62
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.
65
66 =back
67
68 Returns
69
70 =cut
71
72 sub search {
73     my ($self, $query, $page, $count, %options) = @_;
74
75     my $params = $self->get_elasticsearch_params();
76     my %paging;
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};
82     } else {
83         $page = (!defined($page) || ($page <= 0)) ? 0 : $page - 1;
84         $paging{start} = $page * $paging{limit};
85     }
86     $self->store(
87         Catmandu::Store::ElasticSearch->new(
88             %$params,
89             trace_calls => 1,
90         )
91     );
92     my $results = $self->store->bag->search( %$query, %paging );
93     return $results;
94 }
95
96 =head2 search_compat
97
98     my ( $error, $results, $facets ) = $search->search_compat(
99         $query,            $simple_query, \@sort_by,       \@servers,
100         $results_per_page, $offset,       $expanded_facet, $branches,
101         $query_type,       $scan
102       )
103
104 A search interface somewhat compatible with L<C4::Search->getRecords>. Anything
105 that is returned in the query created by build_query_compat will probably
106 get ignored here.
107
108 =cut
109
110 sub search_compat {
111     my (
112         $self,     $query,            $simple_query, $sort_by,
113         $servers,  $results_per_page, $offset,       $expanded_facet,
114         $branches, $query_type,       $scan
115     ) = @_;
116
117     my %options;
118     $options{offset} = $offset;
119     my $results = $self->search($query, undef, $results_per_page, %options);
120
121     # Convert each result into a MARC::Record
122     my (@records, $index);
123     $index = $offset; # opac-search expects results to be put in the
124         # right place in the array, according to $offset
125     $results->each(sub {
126             # The results come in an array for some reason
127             my $marc_json = @_[0]->{record};
128             my $marc = $self->json2marc($marc_json);
129             $records[$index++] = $marc;
130         });
131     # consumers of this expect a name-spaced result, we provide the default
132     # configuration.
133     my %result;
134     $result{biblioserver}{hits} = $results->total;
135     $result{biblioserver}{RECORDS} = \@records;
136     return (undef, \%result, $self->_convert_facets($results->{facets}));
137 }
138
139 =head2 search_auth_compat
140
141     my ( $results, $total ) =
142       $searcher->search_auth_compat( $query, $page, $count, %options );
143
144 This has a similar calling convention to L<search>, however it returns its
145 results in a form the same as L<C4::AuthoritiesMarc::SearchAuthorities>.
146
147 =cut
148
149 sub search_auth_compat {
150     my $self = shift;
151
152     my $database = Koha::Database->new();
153     my $schema   = $database->schema();
154     my $res      = $self->search(@_);
155     my @records;
156     $res->each(
157         sub {
158             my %result;
159             my $record    = @_[0];
160             my $marc_json = $record->{record};
161
162             # I wonder if these should be real values defined in the mapping
163             # rather than hard-coded conversions.
164             $result{authid} = $record->{ Local-Number };
165
166             # TODO put all this info into the record at index time so we
167             # don't have to go and sort it all out now.
168             my $authtypecode = $record->{authtype};
169             my $rs           = $schema->resultset('AuthType')
170               ->search( { authtypecode => $authtypecode } );
171
172             # FIXME there's an assumption here that we will get a result.
173             # the original code also makes an assumption that some provided
174             # authtypecode may sometimes be used instead of the one stored
175             # with the record. It's not documented why this is the case, so
176             # it's not reproduced here.
177             my $authtype           = $rs->single;
178             my $auth_tag_to_report = $authtype->auth_tag_to_report;
179             my $marc               = $self->json2marc($marc_json);
180             my $mainentry          = $marc->field($auth_tag_to_report);
181             my $reported_tag;
182             if ($mainentry) {
183                 foreach ( $mainentry->subfields() ) {
184                     $reported_tag .= '$' . $_->[0] . $_->[1];
185                 }
186             }
187             # Turn the resultset into a hash
188             my %authtype_cols;
189             foreach my $col (@{ $authtype->result_source->columns }) {
190                 $authtype_cols{$col} = $authtype->get_column($col);
191             }
192             $result{authtype}     = $authtype_cols;
193             $result{reported_tag} = $reported_tag;
194
195             # Reimplementing BuildSummary is out of scope because it'll be hard
196             $result{summary} =
197               C4::AuthoritiesMarc::BuildSummary( $marc, $result{authid},
198                 $authtypecode );
199             push @records, $marc;
200         }
201     );
202     return ( \@records, $res->total );
203 }
204
205 =head2 json2marc
206
207     my $marc = $self->json2marc($marc_json);
208
209 Converts the form of marc (based on its JSON, but as a Perl structure) that
210 Catmandu stores into a MARC::Record object.
211
212 =cut
213
214 sub json2marc {
215     my ( $self, $marcjson ) = @_;
216
217     my $marc = MARC::Record->new();
218     $marc->encoding('UTF-8');
219
220     # fields are like:
221     # [ '245', '1', '2', 'a' => 'Title', 'b' => 'Subtitle' ]
222     # conveniently, this is the form that MARC::Field->new() likes
223     foreach $field (@$marcjson) {
224         next if @$field < 5;    # Shouldn't be possible, but...
225         if ( $field->[0] eq 'LDR' ) {
226             $marc->leader( $field->[4] );
227         }
228         else {
229             my $marc_field = MARC::Field->new(@$field);
230             $marc->append_fields($marc_field);
231         }
232     }
233     return $marc;
234 }
235
236 =head2 _convert_facets
237
238     my $koha_facets = _convert_facets($es_facets);
239
240 Converts elasticsearch facets types to the form that Koha expects.
241 It expects the ES facet name to match the Koha type, for example C<itype>,
242 C<au>, C<su-to>, etc.
243
244 =cut
245
246 sub _convert_facets {
247     my ( $self, $es ) = @_;
248
249     return undef if !$es;
250
251     # These should correspond to the ES field names, as opposed to the CCL
252     # things that zebra uses.
253     my %type_to_label = (
254         author   => 'Authors',
255         location => 'Location',
256         itype    => 'ItemTypes',
257         se       => 'Series',
258         subject  => 'Topics',
259         'su-geo' => 'Places',
260     );
261
262     # We also have some special cases, e.g. itypes that need to show the
263     # value rather than the code.
264     my $itypes = Koha::ItemTypes->new();
265     my %special = ( itype => sub { $itypes->get_description_for_code(@_) }, );
266     my @res;
267     while ( ( $type, $data ) = each %$es ) {
268         next if !exists( $type_to_label{$type} );
269         my $facet = {
270             type_id => $type . '_id',
271             expand  => $type,
272             expandable => 1,    # TODO figure how that's supposed to work
273             "type_label_$type_to_label{$type}" => 1,
274             type_link_value                    => $type,
275         };
276         foreach my $term ( @{ $data->{terms} } ) {
277             my $t = $term->{term};
278             my $c = $term->{count};
279             if ( exists( $special{$type} ) ) {
280                 $label = $special{$type}->($t);
281             }
282             else {
283                 $label = $t;
284             }
285             push @{ $facet->{facets} }, {
286                 facet_count       => $c,
287                 facet_link_value  => $t,
288                 facet_title_value => $t . " ($c)",
289                 facet_label_value => $label,    # TODO either truncate this,
290                      # or make the template do it like it should anyway
291                 type_link_value => $type,
292             };
293         }
294         push @res, $facet if exists $facet->{facets};
295     }
296     return \@res;
297 }
298
299
300 1;