Bug 26516: Don't accept incorrect values for copyrightdate/publicationyear
[koha.git] / misc / search_tools / rebuild_elasticsearch.pl
1 #!/usr/bin/perl
2
3 # This inserts records from a Koha database into elastic search
4
5 # Copyright 2014 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 3 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 =head1 NAME
23
24 rebuild_elasticsearch.pl - inserts records from a Koha database into Elasticsearch
25
26 =head1 SYNOPSIS
27
28 B<rebuild_elasticsearch.pl>
29 [B<-c|--commit>=C<count>]
30 [B<-d|--delete>]
31 [B<-r|--reset>]
32 [B<-a|--authorities>]
33 [B<-b|--biblios>]
34 [B<-bn|--bnumber>]
35 [B<-ai|--authid>]
36 [B<-p|--processes>]
37 [B<-v|--verbose>]
38 [B<-h|--help>]
39 [B<--man>]
40
41 =head1 DESCRIPTION
42
43 Inserts records from a Koha database into Elasticsearch.
44
45 =head1 OPTIONS
46
47 =over
48
49 =item B<-c|--commit>=C<count>
50
51 Specify how many records will be batched up before they're added to Elasticsearch.
52 Higher should be faster, but will cause more RAM usage. Default is 5000.
53
54 =item B<-d|--delete>
55
56 Delete the index and recreate it before indexing.
57
58 =item B<-r|--reset>
59
60 Reload mappings from files (specified in koha-conf.xml) before indexing.
61 Implies --delete.
62
63 =item B<-a|--authorities>
64
65 Index the authorities only. Combining this with B<-b> is the same as
66 specifying neither and so both get indexed.
67
68 =item B<-b|--biblios>
69
70 Index the biblios only. Combining this with B<-a> is the same as
71 specifying neither and so both get indexed.
72
73 =item B<-bn|--bnumber>
74
75 Only index the supplied biblionumber, mostly for testing purposes. May be
76 repeated.
77
78 =item B<-ai|--authid>
79
80 Only index the supplied authority id, mostly for testing purposes. May be
81 repeated.
82
83 =item B<-p|--processes>
84
85 Number of processes to use for indexing. This can be used to do more indexing
86 work in parallel on multicore systems. By default, a single process is used.
87
88 =item B<-v|--verbose>
89
90 By default, this program only emits warnings and errors. This makes it talk
91 more. Add more to make it even more wordy, in particular when debugging.
92
93 =item B<-h|--help>
94
95 Help!
96
97 =item B<--man>
98
99 Full documentation.
100
101 =back
102
103 =head1 IMPLEMENTATION
104
105 =cut
106
107 use autodie;
108 use Getopt::Long;
109 use Koha::Script;
110 use C4::Context;
111 use Koha::MetadataRecord::Authority;
112 use Koha::BiblioUtils;
113 use Koha::SearchEngine::Elasticsearch;
114 use Koha::SearchEngine::Elasticsearch::Indexer;
115 use MARC::Field;
116 use MARC::Record;
117 use Modern::Perl;
118 use Pod::Usage;
119
120 my $verbose = 0;
121 my $commit = 5000;
122 my ($delete, $reset, $help, $man, $processes);
123 my ($index_biblios, $index_authorities);
124 my (@biblionumbers,@authids);
125
126 $|=1; # flushes output
127
128 GetOptions(
129     'c|commit=i'    => \$commit,
130     'd|delete'      => \$delete,
131     'r|reset'       => \$reset,
132     'a|authorities' => \$index_authorities,
133     'b|biblios'     => \$index_biblios,
134     'bn|bnumber=i' => \@biblionumbers,
135     'ai|authid=i'  => \@authids,
136     'p|processes=i' => \$processes,
137     'v|verbose+'    => \$verbose,
138     'h|help'        => \$help,
139     'man'           => \$man,
140 );
141
142 # Default is to do both
143 unless ($index_authorities || $index_biblios) {
144     $index_authorities = $index_biblios = 1;
145 }
146
147 if ($processes && ( @biblionumbers || @authids) ) {
148     die "Argument p|processes cannot be combined with bn|bnumber or ai|authid";
149 }
150
151 pod2usage(1) if $help;
152 pod2usage( -exitstatus => 0, -verbose => 2 ) if $man;
153
154 _sanity_check();
155
156 if ($reset){
157     Koha::SearchEngine::Elasticsearch->reset_elasticsearch_mappings;
158     $delete = 1;
159 }
160
161 _verify_index_state($Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX, $delete) if ($index_biblios);
162 _verify_index_state($Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX, $delete) if ($index_authorities);
163
164 my $slice_index = 0;
165 my $slice_count = ( $processes //= 1 );
166 my %iterator_options;
167
168 if ($slice_count > 1) {
169     # Fire up child processes for processing slices from 2 on. This main process will handle slice 1.
170     $slice_index = 0;
171     for (my $proc = 1; $proc < $slice_count; $proc++) {
172         my $pid = fork();
173         die "Failed to fork a child process\n" unless defined $pid;
174         if ($pid == 0) {
175             # Child process, give it a slice to process
176             $slice_index = $proc;
177             last;
178         }
179     }
180     # Fudge the commit count a bit to spread out the Elasticsearch commits
181     $commit *= 1 + 0.10 * $slice_index;
182     _log(1, "Processing slice @{[$slice_index + 1]} of $slice_count\n");
183     $iterator_options{slice} = { index => $slice_index, count => $slice_count };
184 }
185
186 my $next;
187 if ($index_biblios) {
188     _log(1, "Indexing biblios\n");
189     if (@biblionumbers) {
190         $next = sub {
191             my $r = shift @biblionumbers;
192             return () unless defined $r;
193             return ($r, Koha::BiblioUtils->get_from_biblionumber($r, item_data => 1 ));
194         };
195     } else {
196         my $records = Koha::BiblioUtils->get_all_biblios_iterator(%iterator_options);
197         $next = sub {
198             $records->next();
199         }
200     }
201     _do_reindex($next, $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX);
202 }
203 if ($index_authorities) {
204     _log(1, "Indexing authorities\n");
205     if (@authids) {
206         $next = sub {
207             my $r = shift @authids;
208             return () unless defined $r;
209             my $a = Koha::MetadataRecord::Authority->get_from_authid($r);
210             return ($r, $a);
211         };
212     } else {
213         my $records = Koha::MetadataRecord::Authority->get_all_authorities_iterator(%iterator_options);
214         $next = sub {
215             $records->next();
216         }
217     }
218     _do_reindex($next, $Koha::SearchEngine::Elasticsearch::AUTHORITIES_INDEX);
219 }
220
221 if ($slice_index == 0) {
222     # Main process, wait for children
223     for (my $proc = 1; $proc < $processes; $proc++) {
224         wait();
225     }
226 }
227
228 =head1 INTERNAL METHODS
229
230 =head2 _verify_index_state
231
232     _verify_index_state($Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX, 1);
233
234 Checks the index state and recreates it if requested.
235
236 =cut
237
238 sub _verify_index_state {
239     my ( $index_name, $recreate ) = @_;
240
241     _log(1, "Checking state of $index_name index\n");
242     my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new( { index => $index_name } );
243
244     if ($recreate) {
245         _log(1, "Dropping and recreating $index_name index\n");
246         $indexer->drop_index() if $indexer->index_exists();
247         $indexer->create_index();
248     }
249     elsif (!$indexer->index_exists) {
250         # Create index if does not exist
251         $indexer->create_index();
252     } elsif ($indexer->is_index_status_ok) {
253         # Update mapping unless index is some kind of problematic state
254         $indexer->update_mappings();
255     } elsif ($indexer->is_index_status_recreate_required) {
256         warn qq/Index "$index_name" has status "recreate required", suggesting it should be recreated/;
257     }
258 }
259
260 =head2 _do_reindex
261
262     _do_reindex($callback, $Koha::SearchEngine::Elasticsearch::BIBLIOS_INDEX);
263
264 Does the actual reindexing. $callback is a function that always returns the next record.
265 For each index we iterate through the records, committing at specified count
266
267 =cut
268
269 sub _do_reindex {
270     my ( $next, $index_name ) = @_;
271
272     my $indexer = Koha::SearchEngine::Elasticsearch::Indexer->new( { index => $index_name } );
273
274     my $count        = 0;
275     my $commit_count = $commit;
276     my ( @id_buffer, @commit_buffer );
277     while ( my $record = $next->() ) {
278         my $id     = $record->id // $record->authid;
279         my $record = $record->record;
280         $count++;
281         if ( $verbose == 1 ) {
282             _log( 1, "$count records processed\n" ) if ( $count % 1000 == 0);
283         } else {
284             _log( 2, "$id\n" );
285         }
286
287         push @id_buffer,     $id;
288         push @commit_buffer, $record;
289         if ( !( --$commit_count ) ) {
290             _log( 1, "Committing $commit records...\n" );
291             my $response = $indexer->update_index( \@id_buffer, \@commit_buffer );
292             _handle_response($response);
293             $commit_count  = $commit;
294             @id_buffer     = ();
295             @commit_buffer = ();
296             _log( 1, "Commit complete\n" );
297         }
298     }
299
300     # There are probably uncommitted records
301     _log( 1, "Committing final records...\n" );
302     my $response = $indexer->update_index( \@id_buffer, \@commit_buffer );
303     _handle_response($response);
304     _log( 1, "Total $count records indexed\n" );
305 }
306
307 =head2 _sanity_check
308
309     _sanity_check();
310
311 Checks some basic stuff to ensure that it's sane before we start.
312
313 =cut
314
315 sub _sanity_check {
316     # Do we have an elasticsearch block defined?
317     my $conf = C4::Context->config('elasticsearch');
318     die "No 'elasticsearch' block is defined in koha-conf.xml.\n" if ( !$conf );
319 }
320
321 =head2 _handle_response
322
323 Parse the return from update_index and display errors depending on verbosity of the script
324
325 =cut
326
327 sub _handle_response {
328     my ($response) = @_;
329     if( $response->{errors} eq 'true' ){
330         _log( 1, "There were errors during indexing\n" );
331         if ( $verbose > 1 ){
332             foreach my $item (@{$response->{items}}){
333                 next unless defined $item->{index}->{error};
334                 print "Record #" . $item->{index}->{_id} . " " .
335                       $item->{index}->{error}->{reason} . " (" . $item->{index}->{error}->{type} . ") : " .
336                       $item->{index}->{error}->{caused_by}->{type} . " (" . $item->{index}->{error}->{caused_by}->{reason} . ")\n";
337             }
338         }
339     }
340 }
341
342 =head2 _log
343
344     _log($level, "Message\n");
345
346 Output progress information.
347
348 Will output the message if verbosity level is set to $level or more. Will not
349 include a trailing newline automatically.
350
351 =cut
352
353 sub _log {
354     my ($level, $msg) = @_;
355
356     print "[$$] $msg" if ($verbose >= $level);
357 }