Lucy/Searcher.pm

filter: Statementstmt 86.6% 13 / 15 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 90.0% 18 / 20 CC 1 SCAR 0.6
CC
1
Cov
87%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« Lucy/Results.pm ↑ Summary Lucy.pm »
1 package SWISH::Prog::Lucy::Searcher;
2 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 our $VERSION = '0.25';
6  
7 6 ▶use base qw( SWISH::Prog::Searcher );
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 0 ▶use SWISH::3 qw( :constants );
Subroutine BEGIN: called CC=1 SCAR=2.6
11 use SWISH::Prog::Lucy::Results;
12  
13 use Lucy::Search::IndexSearcher;
14 use Lucy::Search::PolySearcher;
15 use Lucy::Analysis::PolyAnalyzer;
16 use Lucy::Search::SortRule;
17 use Lucy::Search::SortSpec;
18 use Path::Class::File::Stat;
19 use Data::Dump qw( dump );
20  
21 # these 2 for nfs_mode==1
22 use Sys::Hostname qw( hostname );
23 use Time::HiRes qw( usleep );
24  
25 use Sort::SQL;
26 use Search::Query;
27 use Search::Query::Dialect::Lucy;
28  
29 __PACKAGE__->mk_accessors(qw( find_relevant_fields qp qp_config nfs_mode ));
30  
31 =head1 NAME
32  
33 SWISH::Prog::Lucy::Searcher - search Swish3 Lucy backend
34  
35 =head1 SYNOPSIS
36
37 my $searcher = SWISH::Prog::Lucy::Searcher->new(
38 invindex => 'path/to/index',
39 max_hits => 1000,
40 find_relevant_fields => 1, # default: 0
41 nfs_mode => 1, # default: 0
42 );
43
44 my $results = $searcher->search( 'foo bar' );
45 while (my $result = $results->next) {
46 printf("%4d %s\n", $result->score, $result->uri);
47 }
48  
49 =head1 DESCRIPTION
50  
51 SWISH::Prog::Lucy::Searcher is an Apache Lucy based Searcher
52 class for Swish3.
53  
54 SWISH::Prog::Lucy::Searcher is not made to replace the more fully-featured
55 Lucy::Search::Searcher class and its friends. Instead, SWISH::Prog::Lucy::Searcher
56 provides a simple API similar to other SWISH::Prog::Searcher-based backends
57 so that you can experiment with alternate
58 storage engines without needing to change much code.
59 When your search application requirements become more complex, the author
60 recommends the switch to using Lucy::Search::Searcher directly.
61  
62 =head1 METHODS
63  
64 Only new and overridden methods are documented here. See
65 the L<SWISH::Prog::Searcher> documentation.
66  
67 =head2 init
68  
69 Called internally by new(). Additional parameters include:
70  
71 =over
72  
73 =item find_relevant_fields I<1|0>
74  
75 Set to true to have the Results object locate the fields
76 that matched the query. Default is 0 (off).
77  
78 =item qp I<search_query_parser_object>
79  
80 Optional. If passed, should be a Search::Query::Parser object.
81 You can get/set the internal parser with the qp() method as well.
82  
83 =item qp_config I<hash_ref>
84  
85 Optional. If set, the internal Search::Query::Parser object
86 will be initialized with I<hash_ref>.
87  
88 =item nfs_mode I<1|0>
89  
90 Set to true if your index is stored on a NFS filesystem. Extra locking
91 precautions are implemented when this mode is on (1). Default is off
92 (0).
93  
94 =back
95  
96 =cut
97  
98 sub init {
99 my $self = shift;
100 $self->SUPER::init(@_);
101  
102 $self->nfs_mode(0) unless defined $self->nfs_mode();
103  
104 $self->{qp_config} ||= {
105 dialect => 'Lucy',
106 croak_on_error => 1, # strict mode on
107 query_class_opts => { debug => $self->debug, },
108 };
109  
110 if ( $self->{qp} ) {
111  
112 # preserve passed-in object for duration
113 $self->{_initial_qp} = $self->{qp};
114 }
115  
116 $self->_init_lucy();
117  
118 return $self;
119 }
120  
121 sub _init_lucy {
122 my $self = shift;
123  
124 # load meta from the first invindex
125 my $invindex = $self->invindex->[0];
126 my $config = $invindex->meta;
127  
128 # cache the meta file stat(), to test if it changes
129 # while the searcher is open. See get_lucy()
130 $self->{swish_xml} = Path::Class::File::Stat->new( $invindex->meta_file );
131 $self->{swish_xml}->use_md5(); # slower but better
132 $self->{_uuid} ||= [ $config->Index->{UUID} || "LUCY_NO_UUID" ];
133  
134 # this does 2 things:
135 # 1: initializes the Lucy Searcher
136 # 2: gives a copy of the Lucy Schema object for field defs
137 my $schema = $self->get_lucy()->get_schema();
138  
139 my $metanames = $config->MetaNames;
140 my $propnames = $config->PropertyNames;
141 my $field_names = [ keys %$metanames, keys %$propnames ];
142 my %fieldtypes;
143 my $doc_prop_map = SWISH_DOC_PROP_MAP();
144 for my $name ( ( @$field_names, keys %$doc_prop_map ) ) {
145 next if exists $fieldtypes{$name};
146 $fieldtypes{$name} = {
147 type => $schema->fetch_type($name),
148 analyzer => $schema->fetch_analyzer($name)
149 };
150 if ( exists $metanames->{$name}->{alias_for} ) {
151 $fieldtypes{$name}->{alias_for}
152 = $metanames->{$name}->{alias_for};
153 }
154 }
155  
156 $self->{_propnames} = $config->get_properties;
157 $self->{_pure_props} = $config->get_pure_properties;
158 $self->{_prop_map} = $config->get_property_map;
159  
160 if ( !$self->{_initial_qp} ) {
161  
162 my %qp_config = %{ $self->qp_config };
163 if ( !exists $qp_config{fields} ) {
164 $qp_config{fields} = \%fieldtypes;
165 }
166 if ( !exists $qp_config{query_class_opts}->{default_field} ) {
167 $qp_config{query_class_opts}->{default_field} = $field_names;
168 }
169  
170 $self->{qp} = Search::Query::Parser->new( %qp_config, );
171 }
172 else {
173 $self->{qp} = $self->{_initial_qp};
174 }
175  
176 $self->debug and warn dump $self;
177  
178 return $self;
179 }
180  
181 =head2 get_propnames
182  
183 Returns array ref of PropertyNames defined for the invindex.
184 The array will not contain any alias names or reserved PropertyNames.
185  
186 =cut
187  
188 sub get_propnames {
189 my $self = shift;
190 return $self->{_pure_props};
191 }
192  
193 sub _get_field_alias_for {
194 my ( $self, $field ) = @_;
195 if ( !exists $self->{_propnames}->{$field} ) {
196 croak "unknown field name: $field";
197 }
198 if ( defined $self->{_propnames}->{$field}->{alias_for} ) {
199 return $self->{_propnames}->{$field}->{alias_for};
200 }
201 return undef;
202 }
203  
204 =head2 search( I<query> [, I<opts> ] )
205  
206 Returns a SWISH::Prog::Lucy::Results object.
207  
208 I<query> is assumed to be query string compatible
209 with Search::Query::Dialect::Lucy.
210  
211 I<opts> is an optional hashref with the following supported
212 key/values:
213  
214 =over
215  
216 =item start
217  
218 The starting position. Default is 0.
219  
220 =item max
221  
222 The ending position. Default is max_hits() as documented
223 in SWISH::Prog::Searcher.
224  
225 =item order
226  
227 Takes a SQL-like text string (like SWISH::Prog::Native::Searcher)
228 or a Lucy::Search::SortSpec object, which will determine
229 the sort order.
230  
231 =item limit
232  
233 Takes an arrayref of arrayrefs. Each child arrayref should
234 have three values: a field (PropertyName) value, a lower limit
235 and an upper limit.
236  
237 =item default_boolop
238  
239 The default boolean connector for parsing I<query>. Valid values
240 are B<AND> and B<OR>. The default is
241 B<AND> (which is different than Lucy::QueryParser, but the
242 same as Swish-e).
243  
244 =back
245  
246 =cut
247  
248 my %boolops = (
249 'AND' => '+',
250 'OR' => '',
251 );
252  
253 sub search {
254 my $self = shift;
255 my $query = shift;
256 croak "query required" unless defined $query;
257 my $opts = shift || {};
258  
259 my $start = $opts->{start} || 0;
260 my $max = $opts->{max} || $self->max_hits;
261 my $order = $opts->{order};
262 my $limits = $opts->{limit} || [];
263 my $boolop = $opts->{default_boolop} || 'AND';
264 if ( !exists $boolops{ uc($boolop) } ) {
265 croak "Unsupported default_boolop: $boolop (should be AND or OR)";
266 }
267 $self->{qp}->default_boolop( $boolops{$boolop} );
268  
269 #warn "query=$query";
270  
271 my $parsed_query = $self->{qp}->parse($query)
272 or croak "Query syntax error: " . $self->{qp}->error;
273  
274 my %hits_args = (
275 offset => $start,
276 num_wanted => $max,
277 );
278  
279 for my $limit (@$limits) {
280 if ( !ref $limit or ref($limit) ne 'ARRAY' or @$limit != 3 ) {
281 croak "poorly-formed limit. should be an array ref of 3 values.";
282 }
283 $parsed_query->add_and_clause(
284 Search::Query::Clause->new(
285 field => $limit->[0],
286 op => '..',
287 value => [ $limit->[1], $limit->[2] ]
288 )
289 );
290 }
291  
292 #carp dump $hits_args{query}->dump;
293  
294 if ($order) {
295 if ( ref $order ) {
296  
297 # assume it is a SortSpec object
298 $hits_args{sort_spec} = $order;
299 }
300 else {
301  
302 my $has_sort_by_score = 0;
303 my $has_sort_by_doc_id = 0;
304  
305 # turn it into a SortSpec
306 my $sort_array = Sort::SQL->parse($order);
307 my @rules;
308 for my $pair (@$sort_array) {
309 my ( $field, $dir ) = @$pair;
310 if ( $self->_get_field_alias_for($field) ) {
311 $field = $self->_get_field_alias_for($field);
312 }
313 my $type;
314 if ( $field eq 'score' or $field =~ m/^(swish)?rank$/ ) {
315 $type = 'score';
316 }
317 else {
318 $type = 'field';
319 }
320  
321 if ( $type eq 'score' ) {
322  
323 $has_sort_by_score++;
324  
325 if ( uc($dir) eq 'DESC' ) {
326 push @rules,
327 Lucy::Search::SortRule->new( type => $type );
328 }
329 else {
330 push @rules,
331 Lucy::Search::SortRule->new(
332 type => $type,
333 reverse => 1
334 );
335 }
336 }
337 else {
338 if ( $field eq 'doc_id' ) {
339 $has_sort_by_doc_id++;
340 }
341 if ( uc($dir) eq 'DESC' ) {
342 push @rules,
343 Lucy::Search::SortRule->new(
344 field => $field,
345 reverse => 1,
346 );
347 }
348 else {
349 push @rules,
350 Lucy::Search::SortRule->new( field => $field, );
351 }
352 }
353 }
354  
355 # always include a sort by score so that we calculate a score.
356 if ( !$has_sort_by_score ) {
357 push @rules, Lucy::Search::SortRule->new( type => 'score' );
358 }
359  
360 # always have doc_id last
361 # http://rectangular.com/pipermail/kinosearch/2010-May/007392.html
362 if ( !$has_sort_by_doc_id ) {
363 push @rules, Lucy::Search::SortRule->new( type => 'doc_id' );
364 }
365  
366 $hits_args{sort_spec}
367 = Lucy::Search::SortSpec->new( rules => \@rules, );
368 }
369 }
370  
371 # turn the Search::Query object into a Lucy object
372 $hits_args{query} = $parsed_query->as_lucy_query;
373 if ( !defined $hits_args{query} ) {
374 croak "Failed to turn '$parsed_query' into a Lucy query";
375 }
376 my $lucy = $self->get_lucy();
377 $self->debug
378 and carp sprintf(
379 "search in %s for [raw] '%s' [lucy] '%s' : %s",
380 $lucy, $parsed_query,
381 dump( $hits_args{query}->dump() ),
382 dump( \%hits_args )
383 );
384 my $compiler
385 = $hits_args{query}->make_compiler( searcher => $lucy, boost => 0 );
386 my $hits = $lucy->hits(%hits_args);
387 my $results = SWISH::Prog::Lucy::Results->new(
388 hits => $hits->total_hits + 0,
389 lucy_hits => $hits,
390 query => $parsed_query,
391 find_relevant_fields => $self->find_relevant_fields,
392 property_map => $self->{_prop_map},
393 id => $self->get_unique_id,
394 );
395 $results->{_compiler} = $compiler;
396 $results->{_searcher} = $lucy;
397 $results->{_args} = \%hits_args;
398 return $results;
399 }
400  
401 =head2 get_unique_id
402  
403 Returns string of all concatenated UUID values from the Searcher's invindex meta
404 descriptions.
405  
406 =cut
407  
408 sub get_unique_id {
409 my $self = shift;
410 my @uuids;
411 my $i = 0;
412 for my $idx ( @{ $self->invindex } ) {
413 push @uuids,
414 ( $idx->meta->Index->{UUID} || $self->{_uuid}->[ $i++ ] );
415 }
416 return join( ',', @uuids );
417 }
418  
419 =head2 get_lucy
420  
421 Returns the internal Lucy::Search::PolySearcher object.
422  
423 =cut
424  
425 sub get_lucy {
426 my $self = shift;
427 my $is_stale = 0;
428 my $i = 0;
429 for my $idx ( @{ $self->invindex } ) {
430 my $uuid = $idx->meta->Index->{UUID} || $self->{_uuid}->[$i];
431  
432 if ( !$self->{lucy} ) {
433  
434 $self->debug and carp "[$i] init lucy";
435 $is_stale++;
436 last;
437  
438 }
439 elsif ( !$self->{_uuid}->[$i] or $self->{_uuid}->[$i] ne $uuid ) {
440  
441 $self->debug
442 and carp sprintf( "[$i] UUID has changed from %s to %s",
443 $self->{_uuid}->[$i], $uuid );
444  
445 $is_stale++;
446  
447 # recache
448 $self->{_uuid}->[$i] = $idx->meta->Index->{UUID};
449  
450 # continue to next loop so _uuid cache gets fully populated
451  
452 }
453 elsif ( $self->{swish_xml}->changed ) {
454  
455 $self->debug and carp "[$i] MD5 sig has changed";
456 $is_stale++;
457  
458 last;
459  
460 }
461 else {
462  
463 $self->debug and carp "[$i] re-using cached Lucy Searcher";
464  
465 }
466  
467 $i++;
468  
469 }
470  
471 if ($is_stale) {
472 $self->_open_lucy;
473 $self->_init_lucy();
474 }
475  
476 return $self->{lucy};
477 }
478  
479 sub _open_lucy {
480 my $self = shift;
481 my @searchers;
482 if ( $self->nfs_mode ) {
483 my $hostname = hostname() or croak "Can't get unique hostname";
484 my $manager = Lucy::Index::IndexManager->new( host => $hostname );
485 my $tries = 0;
486 for my $idx ( @{ $self->invindex } ) {
487 my $searcher;
488 my $err;
489 while ( !$searcher ) {
490 eval {
491 # PolyReader->open is undocumented
492 # but Marvin suggests it to avoid
493 # a memory leak on multiple attempts
494 my $reader = Lucy::Index::PolyReader->open(
495 index => "$idx",
496 manager => $manager,
497 );
498 $searcher
499 = Lucy::Search::IndexSearcher->new( index => $reader,
500 );
501 };
502 if ($@) {
503 usleep(100); # milliseconds before trying again.
504 $tries++;
505 $err = $@;
506 }
507 last if $tries >= 20; # total of 2 seconds
508 }
509 if ($searcher) {
510 push @searchers, $searcher;
511 }
512 else {
513 croak "Failed to open Searcher for $idx: $err";
514 }
515 }
516 }
517 else {
518 for my $idx ( @{ $self->invindex } ) {
519 my $searcher
520 = Lucy::Search::IndexSearcher->new( index => "$idx" );
521 push @searchers, $searcher;
522 }
523 }
524  
525 # assume all the schemas are identical.
526 my $schema = $searchers[0]->get_schema();
527  
528 $self->{lucy} = Lucy::Search::PolySearcher->new(
529 schema => $schema,
530 searchers => \@searchers,
531 );
532  
533 $self->debug and carp "opened new PolySearcher: " . $self->{lucy};
534 }
535  
536 1;
537  
538 __END__
« Lucy/Results.pm ↑ Summary Lucy.pm »