504ccc5856b453768a2b17fc01deb607553c94a5
[srvgit] / Koha / SearchEngine / Elasticsearch / Indexer.pm
1 package Koha::SearchEngine::Elasticsearch::Indexer;
2
3 # Copyright 2013 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 use Carp;
21 use Modern::Perl;
22 use Try::Tiny;
23 use List::Util qw(any);
24 use base qw(Koha::SearchEngine::Elasticsearch);
25 use Data::Dumper;
26
27 # For now just marc, but we can do anything here really
28 use Catmandu::Importer::MARC;
29 use Catmandu::Store::ElasticSearch;
30
31 use Koha::Exceptions;
32 use C4::Context;
33
34 Koha::SearchEngine::Elasticsearch::Indexer->mk_accessors(qw( store ));
35
36 =head1 NAME
37
38 Koha::SearchEngine::Elasticsearch::Indexer - handles adding new records to the index
39
40 =head1 SYNOPSIS
41
42     my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new(
43         { index => Koha::SearchEngine::BIBLIOS_INDEX } );
44     $indexer->drop_index();
45     $indexer->update_index(\@biblionumbers, \@records);
46
47
48 =head1 CONSTANTS
49
50 =over 4
51
52 =item C<Koha::SearchEngine::Elasticsearch::Indexer::INDEX_STATUS_OK>
53
54 Represents an index state where index is created and in a working state.
55
56 =item C<Koha::SearchEngine::Elasticsearch::Indexer::INDEX_STATUS_REINDEX_REQUIRED>
57
58 Not currently used, but could be useful later, for example if can detect when new field or mapping added.
59
60 =item C<Koha::SearchEngine::Elasticsearch::Indexer::INDEX_STATUS_RECREATE_REQUIRED>
61
62 Representings an index state where index needs to be recreated and is not in a working state.
63
64 =back
65
66 =cut
67
68 use constant {
69     INDEX_STATUS_OK => 0,
70     INDEX_STATUS_REINDEX_REQUIRED => 1,
71     INDEX_STATUS_RECREATE_REQUIRED => 2,
72 };
73
74 =head1 FUNCTIONS
75
76 =head2 update_index($biblionums, $records)
77
78     try {
79         $self->update_index($biblionums, $records);
80     } catch {
81         die("Something went wrong trying to update index:" .  $_[0]);
82     }
83
84 Converts C<MARC::Records> C<$records> to Elasticsearch documents and performs
85 an update request for these records on the Elasticsearch index.
86
87 =over 4
88
89 =item C<$biblionums>
90
91 Arrayref of biblio numbers for the C<$records>, the order must be the same as
92 and match up with C<$records>.
93
94 =item C<$records>
95
96 Arrayref of C<MARC::Record>s.
97
98 =back
99
100 =cut
101
102 sub update_index {
103     my ($self, $biblionums, $records) = @_;
104
105     my $conf = $self->get_elasticsearch_params();
106     my $elasticsearch = $self->get_elasticsearch();
107     my $documents = $self->marc_records_to_documents($records);
108     my @body;
109
110     for (my $i=0; $i < scalar @$biblionums; $i++) {
111         my $id = $biblionums->[$i];
112         my $document = $documents->[$i];
113         push @body, {
114             index => {
115                 _id => $id
116             }
117         };
118         push @body, $document;
119     }
120     if (@body) {
121         my $response = $elasticsearch->bulk(
122             index => $conf->{index_name},
123             type => 'data', # is just hard coded in Indexer.pm?
124             body => \@body
125         );
126     }
127     # TODO: handle response
128     return 1;
129 }
130
131 =head2 set_index_status_ok
132
133 Convenience method for setting index status to C<INDEX_STATUS_OK>.
134
135 =cut
136
137 sub set_index_status_ok {
138     my ($self) = @_;
139     $self->index_status(INDEX_STATUS_OK);
140 }
141
142 =head2 is_index_status_ok
143
144 Convenience method for checking if index status is C<INDEX_STATUS_OK>.
145
146 =cut
147
148 sub is_index_status_ok {
149     my ($self) = @_;
150     return $self->index_status == INDEX_STATUS_OK;
151 }
152
153 =head2 set_index_status_reindex_required
154
155 Convenience method for setting index status to C<INDEX_REINDEX_REQUIRED>.
156
157 =cut
158
159 sub set_index_status_reindex_required {
160     my ($self) = @_;
161     $self->index_status(INDEX_STATUS_REINDEX_REQUIRED);
162 }
163
164 =head2 is_index_status_reindex_required
165
166 Convenience method for checking if index status is C<INDEX_STATUS_REINDEX_REQUIRED>.
167
168 =cut
169
170 sub is_index_status_reindex_required {
171     my ($self) = @_;
172     return $self->index_status == INDEX_STATUS_REINDEX_REQUIRED;
173 }
174
175 =head2 set_index_status_recreate_required
176
177 Convenience method for setting index status to C<INDEX_STATUS_RECREATE_REQUIRED>.
178
179 =cut
180
181 sub set_index_status_recreate_required {
182     my ($self) = @_;
183     $self->index_status(INDEX_STATUS_RECREATE_REQUIRED);
184 }
185
186 =head2 is_index_status_recreate_required
187
188 Convenience method for checking if index status is C<INDEX_STATUS_RECREATE_REQUIRED>.
189
190 =cut
191
192 sub is_index_status_recreate_required {
193     my ($self) = @_;
194     return $self->index_status == INDEX_STATUS_RECREATE_REQUIRED;
195 }
196
197 =head2 index_status($status)
198
199 Will either set the current index status to C<$status> and return C<$status>,
200 or return the current index status if called with no arguments.
201
202 =over 4
203
204 =item C<$status>
205
206 Optional argument. If passed will set current index status to C<$status> if C<$status> is
207 a valid status. See L</CONSTANTS>.
208
209 =back
210
211 =cut
212
213 sub index_status {
214     my ($self, $status) = @_;
215     my $key = 'ElasticsearchIndexStatus_' . $self->index;
216
217     if (defined $status) {
218         unless (any { $status == $_ } (
219                 INDEX_STATUS_OK,
220                 INDEX_STATUS_REINDEX_REQUIRED,
221                 INDEX_STATUS_RECREATE_REQUIRED,
222             )
223         ) {
224             Koha::Exceptions::Exception->throw("Invalid index status: $status");
225         }
226         C4::Context->set_preference($key, $status);
227         return $status;
228     }
229     else {
230         return C4::Context->preference($key);
231     }
232 }
233
234 =head2 update_mappings
235
236 Generate Elasticsearch mappings from mappings stored in database and
237 perform a request to update Elasticsearch index mappings. Will throw an
238 error and set index status to C<INDEX_STATUS_RECREATE_REQUIRED> if update
239 failes.
240
241 =cut
242
243 sub update_mappings {
244     my ($self) = @_;
245     my $conf = $self->get_elasticsearch_params();
246     my $elasticsearch = $self->get_elasticsearch();
247     my $mappings = $self->get_elasticsearch_mappings();
248
249     foreach my $type (keys %{$mappings}) {
250         try {
251             my $response = $elasticsearch->indices->put_mapping(
252                 index => $conf->{index_name},
253                 type => $type,
254                 body => {
255                     $type => $mappings->{$type}
256                 }
257             );
258         } catch {
259             $self->set_index_status_recreate_required();
260             my $reason = $_[0]->{vars}->{body}->{error}->{reason};
261             Koha::Exceptions::Exception->throw(
262                 error => "Unable to update mappings for index \"$conf->{index_name}\". Reason was: \"$reason\". Index needs to be recreated and reindexed",
263             );
264         };
265     }
266     $self->set_index_status_ok();
267 }
268
269 =head2 update_index_background($biblionums, $records)
270
271 This has exactly the same API as C<update_index> however it'll
272 return immediately. It'll start a background process that does the adding.
273
274 If it fails to add to Elasticsearch then it'll add to a queue that will cause
275 it to be updated by a regular index cron job in the future.
276
277 =cut
278
279 # TODO implement in the future - I don't know the best way of doing this yet.
280 # If fork: make sure process group is changed so apache doesn't wait for us.
281
282 sub update_index_background {
283     my $self = shift;
284     $self->update_index(@_);
285 }
286
287 =head2 delete_index($biblionums)
288
289 C<$biblionums> is an arrayref of biblionumbers to delete from the index.
290
291 =cut
292
293 sub delete_index {
294     my ($self, $biblionums) = @_;
295
296     if ( !$self->store ) {
297         my $params  = $self->get_elasticsearch_params();
298         $self->store(
299             Catmandu::Store::ElasticSearch->new(
300                 %$params,
301                 index_settings => $self->get_elasticsearch_settings(),
302                 index_mappings => $self->get_elasticsearch_mappings(),
303             )
304         );
305     }
306     $self->store->bag->delete("$_") foreach @$biblionums;
307     $self->store->bag->commit;
308 }
309
310 =head2 delete_index_background($biblionums)
311
312 Identical to L</delete_index($biblionums)>
313
314 =cut
315
316 # TODO: Should be made async
317 sub delete_index_background {
318     my $self = shift;
319     $self->delete_index(@_);
320 }
321
322 =head2 drop_index
323
324 Drops the index from the Elasticsearch server.
325
326 =cut
327
328 sub drop_index {
329     my ($self) = @_;
330     if ($self->index_exists) {
331         my $conf = $self->get_elasticsearch_params();
332         my $elasticsearch = $self->get_elasticsearch();
333         $elasticsearch->indices->delete(index => $conf->{index_name});
334         $self->set_index_status_recreate_required();
335     }
336 }
337
338 =head2 create_index
339
340 Creates the index (including mappings) on the Elasticsearch server.
341
342 =cut
343
344 sub create_index {
345     my ($self) = @_;
346     my $conf = $self->get_elasticsearch_params();
347     my $settings = $self->get_elasticsearch_settings();
348     my $elasticsearch = $self->get_elasticsearch();
349     $elasticsearch->indices->create(
350         index => $conf->{index_name},
351         body => {
352             settings => $settings
353         }
354     );
355     $self->update_mappings();
356 }
357
358 =head2 index_exists
359
360 Checks if index has been created on the Elasticsearch server. Returns C<1> or the
361 empty string to indicate whether index exists or not.
362
363 =cut
364
365 sub index_exists {
366     my ($self) = @_;
367     my $conf = $self->get_elasticsearch_params();
368     my $elasticsearch = $self->get_elasticsearch();
369     return $elasticsearch->indices->exists(
370         index => $conf->{index_name},
371     );
372 }
373
374 1;
375
376 __END__
377
378 =head1 AUTHOR
379
380 =over 4
381
382 =item Chris Cormack C<< <chrisc@catalyst.net.nz> >>
383
384 =item Robin Sheat C<< <robin@catalyst.net.nz> >>
385
386 =back