4 package OpenILS::Application::Storage::Driver::Pg::QueryParser;
5 use OpenILS::Application::Storage::QueryParser;
6 use base 'QueryParser';
7 use OpenILS::Utils::DateTime qw/:datetime/;
8 use OpenSRF::Utils::JSON;
9 use OpenILS::Application::AppUtils;
10 use OpenILS::Utils::CStoreEditor;
11 use OpenSRF::Utils::Logger qw($logger);
13 my $U = 'OpenILS::Application::AppUtils';
16 sub subquery_callback {
17 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
19 return sprintf(' ((%s)) ',
25 OpenILS::Utils::CStoreEditor
27 ->search_actor_search_query({ id => $params })
33 sub filter_group_entry_callback {
34 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
36 return sprintf(' saved_query(%s)',
42 OpenILS::Utils::CStoreEditor
44 ->search_actor_search_filter_group_entry({ id => $params })
51 my ($invocant, $self, $struct, $filter, $params, $negate) = @_;
54 my $negate_flag = ($negate ? '-' : '');
56 for my $param (@$params) {
57 my ($t,$f) = split('-', $param);
59 $treturn .= 'item_type(' . join(',',split('', $t)) . ')' if ($t);
60 $treturn .= ' ' if ($t and $f);
61 $treturn .= 'item_form(' . join(',',split('', $f)) . ')' if ($f);
62 $treturn = '(' . $treturn . ')' if ($t and $f);
63 push(@returns, $treturn) if $treturn;
65 $return = join(' || ', @returns);
66 $return = '(' . $return . ')' if(@returns > 1);
67 $return = $negate_flag.$return if($return);
75 if ($value =~ /^\d/) { # may have to use non-$ quoting
77 $value =~ s/\\/\\\\/g;
80 return "\$_$$\$$value\$_$$\$";
83 sub quote_phrase_value {
88 my $left_anchored = '';
89 my $right_anchored = '';
93 $left_anchored = $1 if $value =~ m/^([*\^])/;
94 $right_anchored = $1 if $value =~ m/([*\$])$/;
96 # We can't use word-boundary bracket expressions if the relevant char
97 # is not actually a "word" characters.
98 $left_wb = $wb if $value =~ m/^\w+/;
99 $right_wb = $wb if $value =~ m/\w+$/;
101 $value =~ s/^[*\^]// if $left_anchored;
102 $value =~ s/[*\$]$// if $right_anchored;
103 $value = quotemeta($value);
104 $value = '^' . $value if $left_anchored eq '^';
105 $value = "$value\$" if $right_anchored eq '$';
106 $value = '[[:<:]]' . $value if $left_wb && !$left_anchored;
107 $value .= '[[:>:]]' if $right_wb && !$right_anchored;
108 return $self->quote_value($value);
115 sub default_preferred_language {
119 $self->custom_data->{default_preferred_language} = $lang if ($lang);
120 return $self->custom_data->{default_preferred_language};
123 sub default_preferred_language_multiplier {
127 $self->custom_data->{default_preferred_language_multiplier} = $lang if ($lang);
128 return $self->custom_data->{default_preferred_language_multiplier};
131 sub max_popularity_importance_multiplier {
135 $self->custom_data->{max_popularity_importance_multiplier} = $max if defined($max);
136 return $self->custom_data->{max_popularity_importance_multiplier};
142 return 0 unless $self->parse_tree;
143 return 0 if @{$self->parse_tree->filters};
144 return 0 if @{$self->parse_tree->modifiers};
145 for my $node ( @{ $self->parse_tree->query_nodes } ) {
146 return 0 if (!ref($node) && $node eq '|');
147 next unless (ref($node));
148 return 0 if ($node->isa('QueryParser::query_plan'));
156 return $self->parse_tree->toSQL;
159 sub dynamic_filters {
163 $self->custom_data->{dynamic_filters} ||= [];
164 push(@{$self->custom_data->{dynamic_filters}}, $new) if ($new);
165 return $self->custom_data->{dynamic_filters};
168 sub dynamic_sorters {
172 $self->custom_data->{dynamic_sorters} ||= [];
173 push(@{$self->custom_data->{dynamic_sorters}}, $new) if ($new);
174 return $self->custom_data->{dynamic_sorters};
177 sub facet_field_id_map {
181 $self->custom_data->{facet_field_id_map} ||= {};
182 $self->custom_data->{facet_field_id_map} = $map if ($map);
183 return $self->custom_data->{facet_field_id_map};
186 sub add_facet_field_id_map {
193 $self->add_facet_field( $class => $field );
194 $self->facet_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
195 $self->facet_field_id_map->{by_class}{$class}{$field} = $id;
198 by_id => { $id => { classname => $class, field => $field, weight => $weight } },
199 by_class => { $class => { $field => $id } }
203 sub facet_field_class_by_id {
207 return $self->facet_field_id_map->{by_id}{$id};
210 sub facet_field_ids_by_class {
215 return undef unless ($class);
218 return [$self->facet_field_id_map->{by_class}{$class}{$field}];
221 return [values( %{ $self->facet_field_id_map->{by_class}{$class} } )];
224 sub search_field_id_map {
228 $self->custom_data->{search_field_id_map} ||= {};
229 $self->custom_data->{search_field_id_map} = $map if ($map);
230 return $self->custom_data->{search_field_id_map};
233 sub search_field_virtual_map {
237 $self->custom_data->{search_field_virtual_map} ||= {};
238 $self->custom_data->{search_field_virtual_map} = $map if ($map);
239 return $self->custom_data->{search_field_virtual_map};
242 sub add_search_field_id_map {
248 my $combined = shift;
250 $self->add_search_field( $class => $field );
251 $self->search_field_id_map->{by_id}{$id} = { classname => $class, field => $field, weight => $weight };
252 $self->search_field_id_map->{by_class}{$class}{$field} = $id;
255 by_id => { $id => { classname => $class, field => $field, weight => $weight } },
256 by_class => { $class => { $field => $id } }
260 sub add_search_field_virtual_map {
266 $self->search_field_virtual_map->{by_virt}{$virtid} ||= [];
267 push @{$self->search_field_virtual_map->{by_virt}{$virtid}}, { real => $realid, weight => $weight };
269 $self->search_field_virtual_map->{by_real}{$realid} ||= [];
270 push @{$self->search_field_virtual_map->{by_real}{$realid}}, { virt => $virtid, weight => $weight };
273 sub search_field_class_by_id {
277 return $self->search_field_id_map->{by_id}{$id};
280 sub search_field_ids_by_class {
285 return undef unless ($class);
288 return [$self->search_field_id_map->{by_class}{$class}{$field}];
291 return [values( %{ $self->search_field_id_map->{by_class}{$class} } )];
294 sub relevance_bumps {
298 $self->custom_data->{rel_bumps} ||= {};
299 $self->custom_data->{rel_bumps} = $bumps if ($bumps);
300 return $self->custom_data->{rel_bumps};
303 sub find_relevance_bumps {
308 return $self->relevance_bumps->{$class}{$field};
311 sub add_relevance_bump {
316 my $multiplier = shift;
319 if (defined($active) and $active eq 'f') {
325 $self->relevance_bumps->{$class}{$field}{$type} = { multiplier => $multiplier, active => $active };
327 return { $class => { $field => { $type => { multiplier => $multiplier, active => $active } } } };
330 sub search_class_weights {
333 my $a_weight = shift;
334 my $b_weight = shift;
335 my $c_weight = shift;
336 my $d_weight = shift;
338 $self->custom_data->{class_weights} ||= {};
339 # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
340 $self->custom_data->{class_weights}->{$class} ||= [0.1, 0.2, 0.4, 1.0];
341 $self->custom_data->{class_weights}->{$class} = [$d_weight, $c_weight, $b_weight, $a_weight] if $a_weight;
342 return $self->custom_data->{class_weights}->{$class};
345 sub search_class_combined {
350 $self->custom_data->{class_combined} ||= {};
351 # Note: This reverses the A-D order, putting D first, because that is how the call actually works in PG
352 $self->custom_data->{class_combined}->{$class} ||= 0;
353 $self->custom_data->{class_combined}->{$class} = 1 if $c && $c =~ /^(?:t|y|1)/i;
354 return $self->custom_data->{class_combined}->{$class};
357 sub class_ts_config {
360 my $lang = shift || 'DEFAULT';
362 my $ts_config = shift;
364 $self->custom_data->{class_ts_config} ||= {};
365 $self->custom_data->{class_ts_config}->{$class} ||= {};
366 $self->custom_data->{class_ts_config}->{$class}->{$lang} ||= {};
367 $self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal} ||= [];
368 $self->custom_data->{class_ts_config}->{$class}->{$lang}->{always} ||= [];
369 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'} ||= {};
370 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal} ||= [];
371 $self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always} ||= [];
374 push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}}, $ts_config unless $always;
375 push @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}}, $ts_config if $always;
379 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{always}};
380 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{$lang}->{normal}} unless $always;
381 if($lang ne 'DEFAULT') {
382 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{always}};
383 push @$return, @{$self->custom_data->{class_ts_config}->{$class}->{'DEFAULT'}->{normal}} unless $always;
388 sub field_ts_config {
392 my $lang = shift || 'DEFAULT';
393 my $ts_config = shift;
395 $self->custom_data->{field_ts_config} ||= {};
396 $self->custom_data->{field_ts_config}->{$class} ||= {};
397 $self->custom_data->{field_ts_config}->{$class}->{$field} ||= {};
398 $self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang} ||= [];
399 $self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'} ||= [];
402 push @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}}, $ts_config;
406 push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{$lang}};
407 if($lang ne 'DEFAULT') {
408 push @$return, @{$self->custom_data->{field_ts_config}->{$class}->{$field}->{'DEFAULT'}};
410 # Make it easy on us: Grab any "always" for the class here. If we have none we grab them all.
411 push @$return, @{$self->class_ts_config($class, $lang, scalar(@$return))};
415 sub initialize_search_field_id_map {
417 my $cmf_list = shift;
419 for my $cmf (@$cmf_list) {
420 __PACKAGE__->add_search_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->search_field));
421 __PACKAGE__->add_facet_field_id_map( $cmf->field_class, $cmf->name, $cmf->id, $cmf->weight ) if ($U->is_true($cmf->facet_field));
424 return $self->search_field_id_map;
427 sub initialize_search_field_virtual_map {
429 my $cmfvm_list = shift;
431 __PACKAGE__->add_search_field_virtual_map( $_->real, $_->virtual, $_->weight )
434 $logger->debug('Virtual field map: ' . Dumper($self->search_field_virtual_map));
435 return $self->search_field_virtual_map;
438 sub initialize_aliases {
440 my $cmsa_list = shift;
442 for my $cmsa (@$cmsa_list) {
444 __PACKAGE__->add_search_class_alias( $cmsa->field_class, $cmsa->alias );
446 my $c = $self->search_field_class_by_id( $cmsa->field );
447 __PACKAGE__->add_search_field_alias( $cmsa->field_class, $c->{field}, $cmsa->alias );
452 sub initialize_relevance_bumps {
454 my $sra_list = shift;
456 for my $sra (@$sra_list) {
457 my $c = $self->search_field_class_by_id( $sra->field );
458 __PACKAGE__->add_relevance_bump( $c->{classname}, $c->{field}, $sra->bump_type, $sra->multiplier, $sra->active );
461 return $self->relevance_bumps;
464 sub initialize_query_normalizers {
466 my $tree = shift; # open-ils.cstore.direct.config.metabib_field_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "cmfinm" : ["norm"] }, "order_by" : [{ "class" : "cmfinm", "field" : "pos" }] }
468 for my $cmfinm ( @$tree ) {
469 my $field_info = $self->search_field_class_by_id( $cmfinm->field );
470 next unless $field_info;
471 __PACKAGE__->add_query_normalizer( $field_info->{classname}, $field_info->{field}, $cmfinm->norm->func, OpenSRF::Utils::JSON->JSON2perl($cmfinm->params) );
475 sub initialize_dynamic_filters {
477 my $list = shift; # open-ils.cstore.direct.config.record_attr_definition.search.atomic { "id" : { "!=" : null } }
479 for my $crad ( @$list ) {
480 __PACKAGE__->dynamic_filters( __PACKAGE__->add_search_filter( $crad->name ) ) if ($U->is_true($crad->filter));
481 __PACKAGE__->dynamic_sorters( $crad->name ) if ($U->is_true($crad->sorter));
485 sub initialize_filter_normalizers {
487 my $tree = shift; # open-ils.cstore.direct.config.record_attr_index_norm_map.search.atomic { "id" : { "!=" : null } }, { "flesh" : 1, "flesh_fields" : { "crainm" : ["norm"] }, "order_by" : [{ "class" : "crainm", "field" : "pos" }] }
489 for my $crainm ( @$tree ) {
490 __PACKAGE__->add_filter_normalizer( $crainm->attr, $crainm->norm->func, OpenSRF::Utils::JSON->JSON2perl($crainm->params) );
494 sub initialize_search_class_weights {
498 for my $search_class (@$classes) {
499 __PACKAGE__->search_class_weights( $search_class->name, $search_class->a_weight, $search_class->b_weight, $search_class->c_weight, $search_class->d_weight );
500 __PACKAGE__->search_class_combined( $search_class->name, $search_class->combined );
504 sub initialize_class_ts_config {
506 my $class_entries = shift;
508 for my $search_class_entry (@$class_entries) {
509 __PACKAGE__->class_ts_config($search_class_entry->field_class,$search_class_entry->search_lang,$U->is_true($search_class_entry->always),$search_class_entry->ts_config);
513 sub initialize_field_ts_config {
515 my $field_entries = shift;
516 my $field_objects = shift;
517 my %field_hash = map { $_->id => $_ } @$field_objects;
519 for my $search_field_entry (@$field_entries) {
520 my $field_object = $field_hash{$search_field_entry->metabib_field};
521 __PACKAGE__->field_ts_config($field_object->field_class,$field_object->name,$search_field_entry->search_lang,$search_field_entry->ts_config);
526 sub initialization_complete {
534 return $_complete if ($_complete);
536 # tsearch rank normalization adjustments. see http://www.postgresql.org/docs/9.0/interactive/textsearch-controls.html#TEXTSEARCH-RANKING for details
537 $self->custom_data->{rank_cd_weight_map} = {
538 CD_logDocumentLength => 1,
539 CD_documentLength => 2,
540 CD_meanHarmonic => 4,
542 CD_logUniqueWords => 16,
546 $self->add_search_modifier( $_ ) for (keys %{ $self->custom_data->{rank_cd_weight_map} });
548 $self->initialize_search_field_id_map( $args{config_metabib_field} )
549 if ($args{config_metabib_field});
551 $self->initialize_search_field_virtual_map( $args{config_metabib_field_virtual_map} )
552 if ($args{config_metabib_field_virtual_map});
554 $self->initialize_aliases( $args{config_metabib_search_alias} )
555 if ($args{config_metabib_search_alias});
557 $self->initialize_relevance_bumps( $args{search_relevance_adjustment} )
558 if ($args{search_relevance_adjustment});
560 $self->initialize_query_normalizers( $args{config_metabib_field_index_norm_map} )
561 if ($args{config_metabib_field_index_norm_map});
563 $self->initialize_dynamic_filters( $args{config_record_attr_definition} )
564 if ($args{config_record_attr_definition});
566 $self->initialize_filter_normalizers( $args{config_record_attr_index_norm_map} )
567 if ($args{config_record_attr_index_norm_map});
569 $self->initialize_search_class_weights( $args{config_metabib_class} )
570 if ($args{config_metabib_class});
572 $self->initialize_class_ts_config( $args{config_metabib_class_ts_map} )
573 if ($args{config_metabib_class_ts_map});
575 $self->initialize_field_ts_config( $args{config_metabib_field_ts_map}, $args{config_metabib_field} )
576 if ($args{config_metabib_field_ts_map} && $args{config_metabib_field});
579 $args{config_metabib_field_index_norm_map} &&
580 $args{search_relevance_adjustment} &&
581 $args{config_metabib_search_alias} &&
582 $args{config_metabib_field} &&
583 $args{config_record_attr_definition}
591 __PACKAGE__->allow_nested_modifiers(1);
593 __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
595 __PACKAGE__->add_search_field_id_map( series => seriestitle => 1 => 1 );
596 __PACKAGE__->add_relevance_bump( series => seriestitle => first_word => 1.5 );
597 __PACKAGE__->add_relevance_bump( series => seriestitle => full_match => 20 );
599 __PACKAGE__->add_search_field_id_map( title => abbreviated => 2 => 1 );
600 __PACKAGE__->add_relevance_bump( title => abbreviated => first_word => 1.5 );
601 __PACKAGE__->add_relevance_bump( title => abbreviated => full_match => 20 );
603 __PACKAGE__->add_search_field_id_map( title => translated => 3 => 1 );
604 __PACKAGE__->add_relevance_bump( title => translated => first_word => 1.5 );
605 __PACKAGE__->add_relevance_bump( title => translated => full_match => 20 );
607 __PACKAGE__->add_search_field_id_map( title => proper => 6 => 1 );
608 __PACKAGE__->add_query_normalizer( title => proper => 'search_normalize' );
609 __PACKAGE__->add_relevance_bump( title => proper => first_word => 1.5 );
610 __PACKAGE__->add_relevance_bump( title => proper => full_match => 20 );
611 __PACKAGE__->add_relevance_bump( title => proper => word_order => 10 );
613 __PACKAGE__->add_search_field_id_map( author => corporate => 7 => 1 );
614 __PACKAGE__->add_relevance_bump( author => corporate => first_word => 1.5 );
615 __PACKAGE__->add_relevance_bump( author => corporate => full_match => 20 );
617 __PACKAGE__->add_facet_field_id_map( author => personal => 8 => 1 );
619 __PACKAGE__->add_search_field_id_map( author => personal => 8 => 1 );
620 __PACKAGE__->add_relevance_bump( author => personal => first_word => 1.5 );
621 __PACKAGE__->add_relevance_bump( author => personal => full_match => 20 );
622 __PACKAGE__->add_query_normalizer( author => personal => 'search_normalize' );
623 __PACKAGE__->add_query_normalizer( author => personal => 'split_date_range' );
625 __PACKAGE__->add_facet_field_id_map( subject => topic => 14 => 1 );
627 __PACKAGE__->add_search_field_id_map( subject => topic => 14 => 1 );
628 __PACKAGE__->add_relevance_bump( subject => topic => first_word => 1 );
629 __PACKAGE__->add_relevance_bump( subject => topic => full_match => 1 );
631 __PACKAGE__->add_search_field_id_map( subject => complete => 16 => 1 );
632 __PACKAGE__->add_relevance_bump( subject => complete => first_word => 1 );
633 __PACKAGE__->add_relevance_bump( subject => complete => full_match => 1 );
635 __PACKAGE__->add_search_field_id_map( keyword => keyword => 15 => 1 );
636 __PACKAGE__->add_relevance_bump( keyword => keyword => first_word => 1 );
637 __PACKAGE__->add_relevance_bump( keyword => keyword => full_match => 1 );
639 __PACKAGE__->add_search_field_virtual_map( 6 => 15 => 5 );
641 __PACKAGE__->class_ts_config( 'series', undef, 1, 'english_nostop' );
642 __PACKAGE__->class_ts_config( 'title', undef, 1, 'english_nostop' );
643 __PACKAGE__->class_ts_config( 'author', undef, 1, 'english_nostop' );
644 __PACKAGE__->class_ts_config( 'subject', undef, 1, 'english_nostop' );
645 __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'english_nostop' );
646 __PACKAGE__->class_ts_config( 'series', undef, 1, 'simple' );
647 __PACKAGE__->class_ts_config( 'title', undef, 1, 'simple' );
648 __PACKAGE__->class_ts_config( 'author', undef, 1, 'simple' );
649 __PACKAGE__->class_ts_config( 'subject', undef, 1, 'simple' );
650 __PACKAGE__->class_ts_config( 'keyword', undef, 1, 'simple' );
652 # French! To test language limiters
653 __PACKAGE__->class_ts_config( 'series', 'fre', 1, 'french_nostop' );
654 __PACKAGE__->class_ts_config( 'title', 'fre', 1, 'french_nostop' );
655 __PACKAGE__->class_ts_config( 'author', 'fre', 1, 'french_nostop' );
656 __PACKAGE__->class_ts_config( 'subject', 'fre', 1, 'french_nostop' );
657 __PACKAGE__->class_ts_config( 'keyword', 'fre', 1, 'french_nostop' );
659 # Not a default config by any means, but good for some testing
660 __PACKAGE__->field_ts_config( 'author', 'personal', 'eng', 'english' );
661 __PACKAGE__->field_ts_config( 'author', 'personal', 'fre', 'french' );
663 __PACKAGE__->add_search_class_alias( keyword => 'kw' );
664 __PACKAGE__->add_search_class_alias( title => 'ti' );
665 __PACKAGE__->add_search_class_alias( author => 'au' );
666 __PACKAGE__->add_search_class_alias( author => 'name' );
667 __PACKAGE__->add_search_class_alias( author => 'dc.contributor' );
668 __PACKAGE__->add_search_class_alias( subject => 'su' );
669 __PACKAGE__->add_search_class_alias( subject => 'bib.subject(?:Title|Place|Occupation)' );
670 __PACKAGE__->add_search_class_alias( series => 'se' );
671 __PACKAGE__->add_search_class_alias( keyword => 'dc.identifier' );
673 __PACKAGE__->add_query_normalizer( author => corporate => 'search_normalize' );
674 __PACKAGE__->add_query_normalizer( keyword => keyword => 'search_normalize' );
676 __PACKAGE__->add_search_field_alias( subject => name => 'bib.subjectName' );
678 #__PACKAGE__->search_class_combined( keyword => 1 );
679 __PACKAGE__->search_class_combined( author => 1 );
682 __PACKAGE__->default_search_class( 'keyword' );
684 # implements EG-specific stored subqueries
685 __PACKAGE__->add_search_filter( 'saved_query', sub { return __PACKAGE__->subquery_callback(@_) } );
686 __PACKAGE__->add_search_filter( 'filter_group_entry', sub { return __PACKAGE__->filter_group_entry_callback(@_) } );
688 # will be retained simply for back-compat
689 __PACKAGE__->add_search_filter( 'format', sub { return __PACKAGE__->format_callback(@_) } );
691 # grumble grumble, special cases against date1 and date2
692 __PACKAGE__->add_search_filter( 'before' );
693 __PACKAGE__->add_search_filter( 'after' );
694 __PACKAGE__->add_search_filter( 'between' );
695 __PACKAGE__->add_search_filter( 'during' );
697 # various filters for limiting in various ways
698 __PACKAGE__->add_search_filter( 'edit_date' );
699 __PACKAGE__->add_search_filter( 'create_date' );
700 __PACKAGE__->add_search_filter( 'statuses' );
701 __PACKAGE__->add_search_filter( 'locations' );
702 __PACKAGE__->add_search_filter( 'location_groups' );
703 __PACKAGE__->add_search_filter( 'bib_source' );
704 __PACKAGE__->add_search_filter( 'badge_orgs' );
705 __PACKAGE__->add_search_filter( 'badges' );
706 __PACKAGE__->add_search_filter( 'site' );
707 __PACKAGE__->add_search_filter( 'pref_ou' );
708 __PACKAGE__->add_search_filter( 'lasso' );
709 __PACKAGE__->add_search_filter( 'my_lasso' );
710 __PACKAGE__->add_search_filter( 'depth' );
711 __PACKAGE__->add_search_filter( 'language' );
712 __PACKAGE__->add_search_filter( 'offset' );
713 __PACKAGE__->add_search_filter( 'limit' );
714 __PACKAGE__->add_search_filter( 'check_limit' );
715 __PACKAGE__->add_search_filter( 'skip_check' );
716 __PACKAGE__->add_search_filter( 'superpage' );
717 __PACKAGE__->add_search_filter( 'superpage_size' );
718 __PACKAGE__->add_search_filter( 'estimation_strategy' );
719 __PACKAGE__->add_search_filter( 'from_metarecord' );
720 __PACKAGE__->add_search_modifier( 'available' );
721 __PACKAGE__->add_search_modifier( 'staff' );
722 __PACKAGE__->add_search_modifier( 'deleted' );
723 __PACKAGE__->add_search_modifier( 'lucky' );
725 # Start from container data (bre, acn, acp): container(bre,bookbag,123,deadb33fdeadb33fdeadb33fdeadb33f)
726 __PACKAGE__->add_search_filter( 'container' );
728 # Start from a list of record ids, either bre or metarecords, depending on the #metabib modifier
729 __PACKAGE__->add_search_filter( 'record_list' );
731 __PACKAGE__->add_search_filter( 'has_browse_entry' );
733 # copy_tag(copy_tag_code,copy_tag_search)
734 __PACKAGE__->add_search_filter( 'copy_tag' );
736 # used internally, but generally not user-settable
737 __PACKAGE__->add_search_filter( 'preferred_language' );
738 __PACKAGE__->add_search_filter( 'preferred_language_weight' );
739 __PACKAGE__->add_search_filter( 'preferred_language_multiplier' );
740 __PACKAGE__->add_search_filter( 'core_limit' );
742 # XXX Valid values to be supplied by SVF
743 __PACKAGE__->add_search_filter( 'sort' );
745 # modifies core query, not configurable
746 __PACKAGE__->add_search_modifier( 'descending' );
747 __PACKAGE__->add_search_modifier( 'ascending' );
748 __PACKAGE__->add_search_modifier( 'nullsfirst' );
749 __PACKAGE__->add_search_modifier( 'nullslast' );
750 __PACKAGE__->add_search_modifier( 'metarecord' );
751 __PACKAGE__->add_search_modifier( 'metabib' );
754 #-------------------------------
755 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan;
756 use base 'QueryParser::query_plan';
757 use OpenSRF::Utils::Logger qw($logger);
758 use OpenILS::Utils::DateTime qw/:datetime/;
760 use OpenILS::Application::AppUtils;
761 use OpenILS::Utils::Normalize qw/search_normalize/;
762 my $apputils = "OpenILS::Application::AppUtils";
764 our %_dfilter_controlled_cache = ();
765 our %_dfilter_stats_cache = ();
766 our $_pg_version = 0;
768 sub dynamic_filter_compile {
769 my ($self, $filter, $params, $negate) = @_;
770 my $e = OpenILS::Utils::CStoreEditor->new;
772 $negate = $negate ? '!' : '';
775 ($_pg_version = $e->json_query({from => ['version']})->[0]->{version}) =~ s/^.+?(\d\.\d).+$/$1/;
779 if ($_pg_version >= 9.2) {
780 if (!scalar keys %_dfilter_stats_cache) {
781 my $data = $e->json_query({from => ['evergreen.pg_statistics', 'record_attr_vector_list', 'vlist']});
782 %_dfilter_stats_cache = map {
783 ( $_->{element}, $_->{frequency} )
784 } grep { $_->{frequency} > 5 } @$data; # Pin floor to 5% of the table
787 $common = 1; # Assume it's expensive
790 if (!exists($_dfilter_controlled_cache{$filter})) {
791 my $crad = $e->retrieve_config_record_attr_definition($filter);
792 my $ccvm_list = $e->search_config_coded_value_map({ctype =>$filter});
794 $_dfilter_controlled_cache{$filter} = $crad->to_bare_hash;
795 $_dfilter_controlled_cache{$filter}{controlled} = scalar @$ccvm_list;
798 my $method = $_dfilter_controlled_cache{$filter}{controlled} ?
799 'search_config_coded_value_map' : 'search_metabib_uncontrolled_record_attr_value';
800 my $attr_field = $_dfilter_controlled_cache{$filter}{controlled} ?
802 my $value_field = $_dfilter_controlled_cache{$filter}{controlled} ?
805 my $attr_objects = $e->$method({ $attr_field => $filter, $value_field => $params });
806 $common = scalar(grep { exists($_dfilter_stats_cache{$_->id}) } @$attr_objects) unless $common;
808 return (sprintf('%s(%s)', $negate,
811 map { $_->id } @$attr_objects
821 for my $f ( qw/preferred_language preferred_language_multiplier preferred_language_weight core_limit check_limit skip_check superpage superpage_size/ ) {
823 $col = 'preferred_language_multiplier' if ($f eq 'preferred_language_weight');
824 my ($filter) = $self->find_filter($f);
825 if ($filter and @{$filter->args}) {
826 $filters{$col} = $filter->args->[0];
830 $self->QueryParser->superpage($filters{superpage}) if ($filters{superpage});
831 $self->QueryParser->superpage_size($filters{superpage_size}) if ($filters{superpage_size});
832 $self->QueryParser->core_limit($filters{core_limit}) if ($filters{core_limit});
834 $logger->debug("Query plan:\n".Dumper($self));
836 my $flat_plan = $self->flatten;
838 # generate the relevance ranking
839 my $rel = '1'; # Default to something simple in case rank_list is empty.
840 if (@{$$flat_plan{rank_list}}) {
843 . join(")\n" . ${spc} x 5 . "+ (", @{$$flat_plan{rank_list}})
845 . ${spc} x 4 . ")+1";
848 # find any supplied sort option
849 my ($sort_filter) = $self->find_filter('sort');
851 $sort_filter = $sort_filter->args->[0];
853 $sort_filter = 'rel';
857 if (($filters{preferred_language} || $self->QueryParser->default_preferred_language) && ($filters{preferred_language_multiplier} || $self->QueryParser->default_preferred_language_multiplier)) {
859 my $pl = $self->QueryParser->quote_value( $filters{preferred_language} ? $filters{preferred_language} : $self->QueryParser->default_preferred_language );
860 $$flat_plan{with} .= ',' if $$flat_plan{with};
861 $$flat_plan{with} .= "lang_with AS (SELECT id FROM config.coded_value_map WHERE ctype = 'item_lang' AND code = $pl)";
862 $lang_join = ",lang_with";
864 my $plw = $filters{preferred_language_multiplier} ? $filters{preferred_language_multiplier} : $self->QueryParser->default_preferred_language_multiplier;
865 $rel = "($rel * COALESCE( NULLIF( FIRST(mrv.vlist \@> ARRAY[lang_with.id]), FALSE )::INT * $plw, 1))";
866 $$flat_plan{uses_mrv} = 1;
870 if ($$flat_plan{uses_mrv}) {
871 $mrv_join = 'INNER JOIN metabib.record_attr_vector_list mrv ON m.source = mrv.source';
875 if ($$flat_plan{uses_mrd}) {
876 $mra_join = 'INNER JOIN metabib.record_attr mrd ON m.source = mrd.id';
879 my $pubdate_join = "LEFT JOIN metabib.record_sorter pubdate_t ON m.source = pubdate_t.source AND attr = 'pubdate'";
882 if ($self->find_modifier('deleted')) {
883 $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND bre.deleted';
884 # The above suffices for filters too when the #deleted modifier
887 $bre_join = 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
891 $desc = 'DESC' if ($self->find_modifier('descending'));
893 my $nullpos = 'NULLS LAST';
894 $nullpos = 'NULLS FIRST' if ($self->find_modifier('nullsfirst'));
896 # Do we have a badges() filter?
898 my ($badge_filter) = $self->find_filter('badges');
899 if ($badge_filter && @{$badge_filter->args}) {
900 $badges = join (',', grep /^\d+$/, @{$badge_filter->args});
903 # Do we have a badge_orgs() filter? (used for calculating popularity)
905 my ($bo_filter) = $self->find_filter('badge_orgs');
906 if ($bo_filter && @{$bo_filter->args}) {
907 $borgs = join (',', grep /^\d+$/, @{$bo_filter->args});
910 # Build the badge-ish WITH query
911 my $pop_with = <<' WITH';
914 ARRAY_AGG(badge) AS badges,
915 SUM(s.score::NUMERIC*b.weight::NUMERIC)/SUM(b.weight::NUMERIC) AS total_score
916 FROM rating.record_badge_score s
917 JOIN rating.badge b ON (
921 $pop_with .= " AND b.id = ANY ('{$badges}')" if ($badges);
922 $pop_with .= " AND b.scope = ANY ('{$borgs}')" if ($borgs);
923 $pop_with .= ') GROUP BY 1)';
925 my $pop_join = $badges ? # inner join if we are restricting via badges()
926 'INNER JOIN pop_with ON ( m.source = pop_with.record )' :
927 'LEFT JOIN pop_with ON ( m.source = pop_with.record )';
929 $$flat_plan{with} .= ',' if $$flat_plan{with};
930 $$flat_plan{with} .= $pop_with;
934 my $pop_extra_sort = '';
935 if (grep {$_ eq $sort_filter} @{$self->QueryParser->dynamic_sorters}) {
936 $rank = "FIRST((SELECT value FROM metabib.record_sorter rbr WHERE rbr.source = m.source and attr = '$sort_filter'))"
937 } elsif ($sort_filter eq 'create_date') {
938 $rank = "FIRST((SELECT create_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
939 } elsif ($sort_filter eq 'edit_date') {
940 $rank = "FIRST((SELECT edit_date FROM biblio.record_entry rbr WHERE rbr.id = m.source))";
941 } elsif ($sort_filter eq 'poprel') {
942 my $max_mult = $self->QueryParser->max_popularity_importance_multiplier() // 2.0;
943 $max_mult = 0.1 if $max_mult < 0.1; # keep it within reasonable bounds,
944 # and avoid the division-by-zero error
945 # you'd get if you allowed it to be
948 if ( $max_mult == 1.0 ) { # no adjustment requested by the configuration
949 $rank = "1.0/($rel)::NUMERIC";
950 } else { # calculate adjustment
952 # Scale the 0-5 effect of popularity badges by providing a multiplier
953 # for the badge average based on the overall maximum
954 # multiplier. Two examples, comparing the effect to the default
955 # $max_mult value of 2.0, which causes a $adjusted_scale value
958 # * Given the default $max_mult of 2.0, the value of
959 # $adjusted_scale will be 0.2 [($max_mult - 1.0) / 5.0].
960 # For a record whose average badge score is the maximum
961 # of 5.0, that would make the relevance multiplier be
963 # 1.0 + (5.0 [average score] * 0.2 [ $adjusted_scale ],
964 # This would have the effect of doubling the effective
965 # relevance of highly popular items.
967 # * Given a $max_mult of 1.1, the value of $adjusted_scale
968 # will be 0.02, meaning that the average badge value will be
969 # multiplied by 0.02 rather than 0.2, then added to 1.0 and
970 # used as a multiplier against the base relevance. Thus a
971 # change of at most 10% to the base relevance for a record
972 # with a 5.0 average badge score. This will allow records
973 # that are naturally very relevant to avoid being pushed
974 # below badge-heavy records.
976 # * Given a $max_mult of 3.0, the value of $adjusted_scale
977 # will be 0.4, meaning that the average badge value will be
978 # multiplied by 0.4 rather than 0.2, then added to 1.0 and
979 # used as a multiplier against the base relevance. Thus a
980 # change of as much as 200% to (or three times the size of)
981 # the base relevance for a record with a 5.0 average badge
982 # score. This in turn will cause badges to outweigh
983 # relevance to a very large degree.
985 # The maximum badge multiplier can be set to a value less than
986 # 1.0; this would have the effect of making less popular items
987 # show up higher in the results. While this is not a likely
988 # option for production use, it could be useful for identifying
989 # interesting long-tail hits, particularly in a database
990 # where enough badges are configured so that very few records
991 # have an overage badge score of zero.
993 my $adjusted_scale = ( $max_mult - 1.0 ) / 5.0;
994 $rank = "1.0/(( $rel ) * (1.0 + (AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) * ${adjusted_scale}::NUMERIC)))::NUMERIC";
996 } elsif ($sort_filter =~ /^pop/) {
997 $rank = '1.0/(AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC)) + 5.0::NUMERIC)::NUMERIC';
998 my $pop_desc = $desc eq 'ASC' ? 'DESC' : 'ASC';
999 $pop_extra_sort = "3 $pop_desc $nullpos,";
1001 # default to rel ranking
1002 $rank = "1.0/($rel)::NUMERIC";
1005 my $key = 'm.source';
1006 $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->modifiers});
1008 my $core_limit = $self->QueryParser->core_limit || 'NULL';
1009 if ($self->find_modifier('lucky')) {
1010 $filters{check_limit} = 1;
1011 $filters{skip_check} = 0;
1016 my $flat_where = $$flat_plan{where};
1017 if ($flat_where ne '') {
1018 $flat_where = "AND (\n" . ${spc} x 5 . $flat_where . "\n" . ${spc} x 4 . ")";
1021 my $final_c_attr_test;
1022 my $c_attr_join = '';
1023 my $c_vis_test = '';
1024 my $pc_vis_test = '';
1026 # copy visibility testing
1027 if (!$self->find_modifier('staff')) {
1028 $pc_vis_test = "c_attrs";
1029 $c_attr_join = ",c_attr"
1032 if ($self->find_modifier('available')) {
1033 push @{$$flat_plan{vis_filter}{'c_attr'}},
1034 "search.calculate_visibility_attribute_test('status','{0,7,12}')";
1037 if (@{$$flat_plan{vis_filter}{c_attr}}) {
1038 $c_vis_test = join(",",@{$$flat_plan{vis_filter}{c_attr}});
1039 $c_attr_join = ',c_attr';
1042 if ($c_vis_test or $pc_vis_test) {
1045 if ($c_vis_test and $pc_vis_test) {
1046 $vis_test = $pc_vis_test . ",". $c_vis_test;
1047 } elsif ($pc_vis_test) {
1048 $vis_test = $pc_vis_test;
1050 $vis_test = $c_vis_test;
1053 # WITH-clause just generates vis test
1054 $$flat_plan{with} .= "\n," if $$flat_plan{with};
1055 $$flat_plan{with} .= "c_attr AS (SELECT (ARRAY_TO_STRING(ARRAY[$vis_test],'&'))::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1057 $final_c_attr_test = 'EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source AND vis_attr_vector @@ c_attr.vis_test)';
1060 if ($self->find_modifier('staff')) { # staff search
1061 $final_c_attr_test ||= 'FALSE';
1062 $final_c_attr_test = '(' . $final_c_attr_test . " OR (" .
1063 "NOT EXISTS (SELECT 1 FROM asset.copy_vis_attr_cache WHERE record = m.source) " .
1064 "AND (bre.vis_attr_vector IS NULL OR NOT ( int4range(0,268435455,'[]') @> ANY(bre.vis_attr_vector) ))".
1066 # We need bre here, regardless
1067 $bre_join ||= 'INNER JOIN biblio.record_entry bre ON m.source = bre.id AND NOT bre.deleted';
1070 my $final_b_attr_test;
1071 my $b_attr_join = '';
1072 my $b_vis_test = '';
1073 my $pb_vis_test = '';
1075 # bib visibility testing
1076 if (!$self->find_modifier('staff')) {
1077 $pb_vis_test = "b_attrs";
1078 $b_attr_join = ",b_attr"
1081 if (@{$$flat_plan{vis_filter}{b_attr}}) {
1082 $b_attr_join = ',b_attr ';
1083 $b_vis_test = join("||'&'||",@{$$flat_plan{vis_filter}{b_attr}});
1086 # bib vis tests are handled a little bit differently, as they're simpler but need special handling
1087 if ($b_vis_test or $pb_vis_test) {
1090 if ($b_vis_test and $pb_vis_test) { # $pb_vis_test supplies a query_int operator at its end
1091 $vis_test = $pb_vis_test . '||'. $b_vis_test;
1092 } elsif ($pb_vis_test) { # here we want to remove it
1093 $vis_test = "RTRIM($pb_vis_test,'|&')";
1095 $vis_test = $b_vis_test;
1098 # WITH-clause just generates vis test
1099 $$flat_plan{with} .= "\n," if $$flat_plan{with};
1100 $$flat_plan{with} .= "b_attr AS (SELECT ($vis_test)::query_int AS vis_test FROM asset.patron_default_visibility_mask() x)";
1102 # These are magic numbers... see: search.calculate_visibility_attribute() UDF
1103 $final_b_attr_test = '(b_attr.vis_test IS NULL OR bre.vis_attr_vector @@ b_attr.vis_test)';
1106 if ($final_c_attr_test or $final_b_attr_test) { # something...
1107 if ($final_c_attr_test and $final_b_attr_test) { # both!
1108 my $plan = "($final_c_attr_test) OR ($final_b_attr_test)";
1109 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $plan . "\n" . ${spc} x 4 . ")";
1110 } elsif ($final_c_attr_test) { # just copies...
1111 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $final_c_attr_test . "\n" . ${spc} x 4 . ")";
1112 } else { # just bibs...
1113 $flat_where .= "\n" . ${spc} x 4 . "AND (\n" . ${spc} x 5 . $final_b_attr_test . "\n" . ${spc} x 4 . ")";
1117 my $with = $$flat_plan{with};
1118 $with= "\nWITH $with" if $with;
1120 # Need an array for query parser db function; this gives a better plan
1121 # than the ARRAY_AGG(DISTINCT m.source) option as of PostgreSQL 9.1
1122 my $agg_records = 'ARRAY[m.source] AS records';
1123 if ($key =~ /metarecord/) {
1124 # metarecord searches still require the ARRAY_AGG approach
1125 $agg_records = 'ARRAY_AGG(DISTINCT m.source) AS records';
1134 CASE WHEN cardinality(records) = 1 THEN records[1] ELSE NULL END AS record,
1136 NULL::INT AS checked,
1137 NULL::INT AS visible,
1138 NULL::INT AS deleted,
1139 NULL::INT AS excluded,
1142 FROM (SELECT $key AS id,
1144 ${rel}::NUMERIC AS rel,
1146 FIRST(pubdate_t.value) AS tie_break,
1147 STRING_AGG(ARRAY_TO_STRING(pop_with.badges,','),',') AS badges,
1148 AVG(COALESCE(pop_with.total_score::NUMERIC,0.0::NUMERIC))::NUMERIC(2,1) AS popularity
1149 FROM metabib.metarecord_source_map m
1162 ORDER BY 4 $desc $nullpos, $pop_extra_sort 5 DESC $nullpos, 3 DESC
1165 ) (SELECT * FROM w LIMIT $filters{check_limit} OFFSET $filters{skip_check})
1167 SELECT NULL,NULL,NULL,COUNT(*),COUNT(*),COUNT(*),0,0,NULL,NULL FROM w;
1170 warn $sql if $self->QueryParser->debug;
1175 sub is_org_visible {
1177 return 0 if (!$U->is_true($org->opac_visible));
1179 my $non_inherited_vis_gf = shift || $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1180 return 1 if ($U->is_true($non_inherited_vis_gf->enabled));
1182 while ($org = $org->parent_ou) {
1183 return 0 if (!$U->is_true($org->opac_visible));
1190 my $kids = $t->children;
1191 if ($kids && @$kids) {
1192 map {$_->parent_ou($t); flesh_parents($_)} @$kids;
1196 sub unflesh_parents {
1198 my $kids = $t->children;
1199 if ($kids && @$kids) {
1200 map {$_->parent_ou($t->id); unflesh_parents($_)} @$kids;
1207 die 'ERROR: nesting too deep or boolean list too long' if ($self->plan_level > 40);
1209 my $from = shift || '';
1210 my $where = shift || '';
1212 my %vis_filter = ( c_attr => [], b_attr => [] );
1218 for my $node ( @{$self->query_nodes} ) {
1221 if ($node->isa( 'QueryParser::query_plan::node' )) {
1223 unless (@{$node->only_atoms}) {
1224 push @rank_list, '1';
1231 if (@{$node->fields} > 0) {
1232 @bump_fields = @{$node->fields};
1234 @field_ids = grep defined, (
1236 $self->QueryParser->search_field_ids_by_class(
1237 $node->classname, $_
1242 @bump_fields = @{$self->QueryParser->search_fields->{$node->classname}};
1245 # use search_field_list to handle virtual index defs
1246 my $search_field_list = $self->QueryParser->search_field_ids_by_class($node->classname);
1247 $search_field_list = [@field_ids] if (@field_ids);
1249 my $table = $node->table;
1250 my $ctable = $node->combined_table;
1251 my $talias = $node->table_alias;
1253 my $node_rank = 'COALESCE(' . $node->rank . " * ${talias}.weight * 1000, 0.0)";
1255 $from .= "\n" . ${spc} x 4 ."LEFT JOIN (\n"
1256 . ${spc} x 5 . "SELECT fe.*, fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* search */\n"
1257 . ${spc} x 6 . "FROM $table AS fe\n"
1258 . ${spc} x 7 . "JOIN config.metabib_field AS fe_weight ON (fe_weight.id = fe.field)";
1260 if ($node->dummy_count < @{$node->only_atoms} ) {
1261 $with .= ",\n " if $with;
1262 $with .= "${talias}_xq AS (SELECT ". $node->tsquery ." AS tsq,". $node->tsquery_rank ." AS tsq_rank )";
1263 if ($node->combined_search) {
1264 $from .= "\n" . ${spc} x 7 . "JOIN $ctable AS com ON (com.record = fe.source";
1266 $from .= " AND com.metabib_field IN (" . join(',',@field_ids) . "))";
1268 $from .= " AND com.metabib_field IS NULL)";
1270 $from .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (com.index_vector @@ ${talias}_xq.tsq)";
1272 $from .= "\n" . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)";
1275 $from .= "\n" . ${spc} x 7 . ", (SELECT NULL::tsquery AS tsq, NULL::tsquery AS tsq_rank ) AS ${talias}_xq";
1279 $from .= "\n" . ${spc} x 6 . "WHERE fe_weight.id IN (" .
1280 join(',', @field_ids) . ")";
1283 # Even though virtual fields have all the real field data in
1284 # their combined version, and thus a search against the real
1285 # fields is not necessary to match records, we still want to
1286 # UNION them in so we can get their virtual weight if they
1287 # would match a search directly against them.
1288 if ($node->dummy_count < @{$node->only_atoms} ) { # no point in searching real fields with no search terms
1289 for my $possible_vfield (@$search_field_list) {
1290 my $real_fields = $self->QueryParser->search_field_virtual_map->{by_virt}->{$possible_vfield};
1291 if ($real_fields and @$real_fields) { # this is a virt field
1292 my %vtable_field_map;
1294 # UNION in the others ... group by class
1295 for my $real_field (@$real_fields) {
1296 my $natural_field = $self->QueryParser->search_field_id_map->{by_id}{$$real_field{real}};
1298 $node->add_vfield($$real_field{real});
1299 $logger->debug("Looking up virtual field for real field $$real_field{real}");
1300 my $vtable = $node->table(
1302 ->search_field_class_by_id($$real_field{real})
1305 $vtable_field_map{$vtable} ||= [];
1306 push(@{$vtable_field_map{$vtable}}, $$real_field{real})
1307 if ($$real_field{weight} != $$natural_field{weight});
1310 for my $vtable (keys %vtable_field_map) {
1311 my $rfields = $vtable_field_map{$vtable};
1312 next unless (@$rfields);
1314 # NOTE: only real fields that match the (component) tsquery will
1315 # get to contribute to and increased rank for the record.
1316 $from .= "\n" . ${spc} x 8 . "UNION ALL\n"
1317 . ${spc} x 5 . "SELECT fe.id, fe.source, fe.field, fe.value, fe.index_vector, "
1318 . "fe_weight.weight, ${talias}_xq.tsq, ${talias}_xq.tsq_rank /* virtual field addition */\n"
1319 . ${spc} x 6 . "FROM $vtable AS fe\n"
1320 . ${spc} x 7 . "JOIN config.metabib_field_virtual_map AS fe_weight ON ("
1321 ."fe_weight.virtual = $possible_vfield AND "
1322 ."fe_weight.real IN (".join(',',@$rfields).") AND "
1323 ."fe_weight.real = fe.field)\n"
1324 . ${spc} x 7 . "JOIN ${talias}_xq ON (fe.index_vector @@ ${talias}_xq.tsq)"
1331 $from .= "\n" . ${spc} x 4 . ") AS $talias ON (m.source = ${talias}.source)";
1336 for my $field ( @bump_fields ) {
1337 my $bumps = $self->QueryParser->find_relevance_bumps( $node->classname => $field );
1338 for my $b (keys %$bumps) {
1339 next if (!$$bumps{$b}{active});
1340 next if ($used_bumps{$b});
1341 $used_bumps{$b} = 1;
1343 next if ($$bumps{$b}{multiplier} == 1); # optimization to remove unneeded bumps
1345 push @bumpmults, $$bumps{$b}{multiplier};
1349 if(scalar @bumps > 0 && scalar @{$node->only_positive_atoms} > 0) {
1350 # Note: Previous rank function used search_normalize outright. Duplicating that here.
1351 $node_rank .= "\n" . ${spc} x 5 . "* COALESCE(evergreen.rel_bump(('{' || quote_literal(search_normalize(";
1352 $node_rank .= join(")) || ',' || quote_literal(search_normalize(",map { $self->QueryParser->quote_phrase_value($_->content) } @{$node->only_positive_atoms});
1353 $node_rank .= ")) || '}')::TEXT[], " . $node->table_alias . ".value, '{" . join(",",@bumps) . "}'::TEXT[], '{" . join(",",@bumpmults) . "}'::NUMERIC[]),1.0)";
1357 $NOT = 'NOT ' if $node->negate;
1359 $where .= "$NOT(" . $talias . ".id IS NOT NULL";
1360 if (@{$node->phrases}) {
1361 $where .= ' AND ' . join(' AND ', map {
1362 "${talias}.value ~* ".$self->QueryParser->quote_phrase_value($_, 1)
1363 } @{$node->phrases});
1365 for my $atom (@{$node->only_real_atoms}) {
1366 next unless $atom->{content} && $atom->{content} =~ /(^\^|\$$)/;
1367 $where .= " AND ${talias}.value ~* ".$self->QueryParser->quote_phrase_value($atom->{content});
1372 push @rank_list, $node_rank;
1374 } elsif ($node->isa( 'QueryParser::query_plan::facet' )) {
1376 my $talias = $node->table_alias;
1379 if (@{$node->fields} > 0) {
1380 push(@field_ids, $self->QueryParser->facet_field_ids_by_class( $node->classname, $_ )->[0]) for (@{$node->fields});
1382 @field_ids = @{ $self->QueryParser->facet_field_ids_by_class( $node->classname ) };
1385 my $join_type = ($node->negate or !$self->top_plan) ? 'LEFT' : 'INNER';
1386 $from .= "\n${spc}$join_type JOIN /* facet */ metabib.facet_entry $talias ON (\n"
1387 . ${spc} x 2 . "m.source = ${talias}.source\n"
1388 . ${spc} x 2 . "AND SUBSTRING(${talias}.value,1,1024) IN ("
1389 . join(",", map { $self->QueryParser->quote_value($_) } @{$node->values}) . ")\n"
1390 . ${spc} x 2 ."AND ${talias}.field IN (". join(',', @field_ids) . ")\n"
1393 if ($join_type ne 'INNER') {
1394 my $NOT = $node->negate ? '' : ' NOT';
1395 $where .= "${talias}.id IS$NOT NULL";
1396 } elsif ($where ne '') {
1397 # Strip extra joiner
1398 $where =~ s/(\s|\n)+(AND|OR)\s$//;
1402 my $subnode = $node->flatten;
1404 # strip the trailing bool from the previous loop if there is
1405 # nothing to add to the where within this loop.
1406 if ($$subnode{where} eq '') {
1407 $where =~ s/(\s|\n)+(AND|OR)\s$//;
1410 push(@rank_list, @{$$subnode{rank_list}});
1411 $from .= $$subnode{from};
1414 $NOT = 'NOT ' if $node->negate;
1416 if ($$subnode{where} ne '') {
1418 . ${spc} x ($self->plan_level + 6) . $$subnode{where} . "\n"
1419 . ${spc} x ($self->plan_level + 5) . ')';
1422 if ($$subnode{with}) {
1423 $with .= ",\n " if $with;
1424 $with .= $$subnode{with};
1427 $uses_bre = $$subnode{uses_bre};
1428 $uses_mrd = $$subnode{uses_mrd};
1429 $uses_mrv = $$subnode{uses_mrv};
1433 warn "flatten(): appending WHERE bool to: $where\n" if $self->QueryParser->debug;
1436 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'AND ' if ($node eq '&');
1437 $where .= "\n" . ${spc} x ( $self->plan_level + 5 ) . 'OR ' if ($node eq '|');
1442 my $joiner = "\n" . ${spc} x ( $self->plan_level + 5 ) . ($self->joiner eq '&' ? 'AND ' : 'OR ');
1444 my ($depth_filter) = grep { $_->name eq 'depth' } @{$self->filters};
1445 if ($depth_filter and @{$depth_filter->args} == 1) {
1446 $depth_filter = $depth_filter->args->[0];
1449 my $ot = $U->get_org_tree;
1451 my $negate = 'FALSE';
1453 my ($site_filter) = grep { $_->name eq 'site' } @{$self->filters};
1454 if ($site_filter and @{$site_filter->args} == 1) {
1455 $negate = $site_filter->negate ? 'TRUE' : 'FALSE';
1457 my $sitename = $site_filter->args->[0];
1458 $site_org = $U->find_org_by_shortname($ot, $sitename) || $ot;
1461 my $dorgs = $U->get_org_descendants($site_org->id, $depth_filter);
1462 my $aorgs = $U->get_org_ancestors($site_org->id);
1465 if (!$self->find_modifier('staff')) {
1466 my $non_inherited_vis_gf = $U->get_global_flag('opac.org_unit.non_inherited_visibility');
1467 $dorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$dorgs ];
1468 $aorgs = [ grep { is_org_visible($U->find_org($ot,$_), $non_inherited_vis_gf) } @$aorgs ];
1470 unflesh_parents($ot);
1472 push @{$vis_filter{'c_attr'}},
1473 "search.calculate_visibility_attribute_test('circ_lib','{".join(',', @$dorgs)."}',$negate)";
1475 if (!$self->find_filter('locations') && !$self->find_filter('location_groups')) {
1476 my $lorgs = [@$aorgs];
1477 my $luri_as_copy_gf = $U->get_global_flag('opac.located_uri.act_as_copy');
1478 push @$lorgs, @$dorgs if ($luri_as_copy_gf and $U->is_true($luri_as_copy_gf->enabled));
1481 push @{$vis_filter{'b_attr'}},
1482 "search.calculate_visibility_attribute_test('luri_org','{".join(',', @$lorgs)."}',$negate)";
1487 # for each dynamic filter, build more of the WHERE clause
1488 for my $filter (@{$self->filters}) {
1489 my $NOT = $filter->negate ? 'NOT ' : '';
1490 if (grep { $_ eq $filter->name } @{ $self->QueryParser->dynamic_filters }) {
1492 my $fname = $filter->name;
1493 $fname = 'item_lang' if $fname eq 'language'; #XXX filter aliases
1495 warn "flatten(): processing dynamic filter ". $filter->name ."\n"
1496 if $self->QueryParser->debug;
1499 ($vlist_query, $common) = $self->dynamic_filter_compile( $fname, $filter->args, $filter->negate );
1501 # bool joiner for intra-plan nodes/filters
1502 push(@dlist, $self->joiner) if @dlist;
1503 push(@dlist, $vlist_query);
1506 if ($filter->name eq 'before') {
1507 if (@{$filter->args} == 1) {
1508 $where .= $joiner if $where ne '';
1509 $where .= "${NOT}COALESCE(pubdate_t.value <= "
1510 . $self->QueryParser->quote_value($filter->args->[0])
1513 } elsif ($filter->name eq 'after') {
1514 if (@{$filter->args} == 1) {
1515 $where .= $joiner if $where ne '';
1516 $where .= "${NOT}COALESCE(pubdate_t.value >= "
1517 . $self->QueryParser->quote_value($filter->args->[0])
1520 } elsif ($filter->name eq 'during') {
1521 if (@{$filter->args} == 1) {
1522 $where .= $joiner if $where ne '';
1523 $where .= "${NOT}COALESCE("
1524 . $self->QueryParser->quote_value($filter->args->[0])
1525 . " BETWEEN pubdate_t.value AND (mrd.attrs->'date2'), false)";
1528 } elsif ($filter->name eq 'between') {
1529 if (@{$filter->args} == 2) {
1530 $where .= $joiner if $where ne '';
1531 $where .= "${NOT}COALESCE(pubdate_t.value BETWEEN "
1532 . $self->QueryParser->quote_value($filter->args->[0])
1534 . $self->QueryParser->quote_value($filter->args->[1])
1537 } elsif ($filter->name eq 'container') {
1538 if (@{$filter->args} >= 3) {
1539 my ($class, $ctype, $cid, $token) = @{$filter->args};
1542 my $rec_field = 'ci.target_biblio_record_entry';
1543 if ($class eq 'bre') {
1544 $class = 'biblio_record_entry';
1545 } elsif ($class eq 'acn') {
1546 $class = 'call_number';
1547 $rec_field = 'cn.record';
1548 $rec_join = 'JOIN asset.call_number cn ON (ci.target_call_number = cn.id)';
1549 } elsif ($class eq 'acp') {
1551 $rec_field = 'cn.record';
1552 $rec_join = 'JOIN asset.copy cp ON (ci.target_copy = cp.id) JOIN asset.call_number cn ON (cp.call_number = cn.id)';
1558 my ($u,$e) = $apputils->checksesperm($token) if ($token);
1559 $perm_join = ' OR c.owner = ' . $u->id if ($u && !$e);
1561 my $filter_alias = "$filter";
1562 $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1563 $filter_alias =~ s/\|/_/go;
1565 $with .= ",\n " if $with;
1566 $with .= "container_${filter_alias} AS (\n";
1567 $with .= " SELECT $rec_field AS record FROM container.${class}_bucket_item ci\n"
1568 . " JOIN container.${class}_bucket c ON (c.id = ci.bucket) $rec_join\n"
1569 . " WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1570 . " AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1571 . " AND (c.pub IS TRUE$perm_join)\n";
1572 if ($class eq 'copy') {
1574 . " SELECT pr.peer_record AS record FROM container.copy_bucket_item ci\n"
1575 . " JOIN container.copy_bucket c ON (c.id = ci.bucket)\n"
1576 . " JOIN biblio.peer_bib_copy_map pr ON ci.target_copy = pr.target_copy\n"
1577 . " WHERE c.btype = " . $self->QueryParser->quote_value($ctype) . "\n"
1578 . " AND c.id = " . $self->QueryParser->quote_value($cid) . "\n"
1579 . " AND (c.pub IS TRUE$perm_join)\n";
1583 my $optimize_join = 1 if $self->top_plan and !$NOT;
1584 $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN container_${filter_alias} ON container_${filter_alias}.record = m.source";
1586 if (!$optimize_join) {
1587 $where .= $joiner if $where ne '';
1588 $where .= "(container_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1592 } elsif ($filter->name eq 'copy_tag') {
1593 my $valid_copy_tag_search = 0;
1596 if (@{$filter->args} >= 2) { # must have at least two parts, tag (or *) and terms
1597 my @fargs = @{$filter->args};
1598 $copy_tag_type = shift(@fargs);
1599 $tag_value = join(' ', @fargs);
1600 $valid_copy_tag_search = 1;
1602 if ($valid_copy_tag_search) {
1603 my $norm_value = search_normalize($tag_value);
1604 my @tokens = split /\s+/, $norm_value;
1606 my $filter_alias = "$filter";
1607 $filter_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1608 $filter_alias =~ s/\|/_/go;
1610 $with .= ",\n " if $with;
1611 $with .= "copy_tag_${filter_alias} AS (\n";
1612 $with .= " SELECT cn.record AS record FROM config.copy_tag_type cctt\n";
1613 $with .= " JOIN asset.copy_tag acpt ON (cctt.code = acpt.tag_type)\n";
1614 $with .= " JOIN asset.copy_tag_copy_map acptcm ON (acpt.id = acptcm.tag)\n";
1615 $with .= " JOIN asset.copy cp ON (acptcm.copy = cp.id)\n";
1616 $with .= " JOIN asset.call_number cn ON (cp.call_number = cn.id)\n";
1617 $with .= " WHERE 1 = 1 \n";
1618 $with .= " AND cp.circ_lib IN (" . join(',', @$dorgs) . ")\n";
1619 if ($copy_tag_type ne '*') {
1620 $with .= " AND cctt.code = " . $self->QueryParser->quote_value($copy_tag_type) . "\n";
1623 $with .= ' AND acpt.value @@ to_tsquery(' . $self->QueryParser->quote_value(join(' & ', @tokens)) . ")\n";
1625 if (!$self->find_modifier('staff')) {
1626 $with .= " AND acpt.pub IS TRUE\n";
1630 my $optimize_join = 1 if $self->top_plan and !$NOT;
1631 $from .= "\n" . ${spc} x 3 . ( $optimize_join ? 'INNER' : 'LEFT') . " JOIN copy_tag_${filter_alias} ON copy_tag_${filter_alias}.record = m.source";
1633 if (!$optimize_join) {
1634 $where .= $joiner if $where ne '';
1635 $where .= "(copy_tag_${filter_alias} IS " . ( $NOT ? 'NULL)' : 'NOT NULL)');
1638 } elsif ($filter->name eq 'record_list') {
1639 if (@{$filter->args} > 0) {
1640 my $key = 'm.source';
1641 $key = 'm.metarecord' if (grep {$_->name eq 'metarecord' or $_->name eq 'metabib'} @{$self->QueryParser->parse_tree->modifiers});
1642 $where .= $joiner if $where ne '';
1643 $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1646 } elsif ($filter->name eq 'locations') {
1647 if (@{$filter->args} > 0) {
1648 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1649 my $filter_args = join(",", map(int, @{$filter->args}));
1650 push @{$vis_filter{'c_attr'}},
1651 "search.calculate_visibility_attribute_test('location','{$filter_args}',$negate)";
1654 } elsif ($filter->name eq 'location_groups') {
1655 if (@{$filter->args} > 0) {
1656 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1657 my $filter_args = join(",", map(int, @{$filter->args}));
1658 push @{$vis_filter{'c_attr'}},
1659 "search.calculate_visibility_attribute_test('location',(SELECT ARRAY_AGG(location) FROM asset.copy_location_group_map WHERE lgroup IN ($filter_args)),$negate)";
1662 } elsif ($filter->name eq 'statuses') {
1663 if (@{$filter->args} > 0) {
1664 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1665 push @{$vis_filter{'c_attr'}},
1666 "search.calculate_visibility_attribute_test('status','{".join(',', @{$filter->args})."}',$negate)";
1669 } elsif ($filter->name eq 'has_browse_entry') {
1670 if (@{$filter->args} >= 2) {
1671 my $entry = int(shift @{$filter->args});
1672 my $fields = join(",", map(int, @{$filter->args}));
1673 $from .= "\n" . $spc x 3 . sprintf("INNER JOIN metabib.browse_entry_def_map mbedm ON (mbedm.source = m.source AND mbedm.entry = %d AND mbedm.def IN (%s))", $entry, $fields);
1675 } elsif ($filter->name eq 'edit_date' or $filter->name eq 'create_date') {
1676 # bre.create_date and bre.edit_date filtering
1677 my $datefilter = $filter->name;
1681 if ($filter && $filter->args && scalar(@{$filter->args}) > 0 && scalar(@{$filter->args}) < 3) {
1682 my ($cstart, $cend) = @{$filter->args};
1684 if (!$cstart and !$cend) {
1685 # useless use of filter
1686 } elsif (!$cstart or $cstart eq '-infinity') { # no start supplied
1687 if ($cend eq 'infinity') {
1688 # useless use of filter
1691 $cend = clean_ISO8601($cend);
1692 $where .= $joiner if $where ne '';
1693 $where .= "bre.$datefilter <= \$_$$\$$cend\$_$$\$";
1696 } elsif (!$cend or $cend eq 'infinity') { # no end supplied
1697 if ($cstart eq '-infinity') {
1698 # useless use of filter
1699 } else { # "after $cstart"
1700 $cstart = clean_ISO8601($cstart);
1701 $where .= $joiner if $where ne '';
1702 $where .= "bre.$datefilter >= \$_$$\$$cstart\$_$$\$";
1704 } else { # both supplied
1705 # "between $cstart and $cend"
1706 $cstart = clean_ISO8601($cstart);
1707 $cend = clean_ISO8601($cend);
1708 $where .= $joiner if $where ne '';
1709 $where .= "bre.$datefilter BETWEEN \$_$$\$$cstart\$_$$\$ AND \$_$$\$$cend\$_$$\$";
1712 } elsif ($filter->name eq 'bib_source') {
1713 if (@{$filter->args} > 0) {
1715 my $negate = $filter->negate ? 'TRUE' : 'FALSE';
1716 push @{$vis_filter{'b_attr'}},
1717 "search.calculate_visibility_attribute_test('source','{".join(',', @{$filter->args})."}',$negate)";
1719 } elsif ($filter->name eq 'from_metarecord') {
1720 if (@{$filter->args} > 0) {
1721 my $key = 'm.metarecord';
1722 $where .= $joiner if $where ne '';
1723 $where .= "$key ${NOT}IN (" . join(',', map { $self->QueryParser->quote_value($_) } @{$filter->args}) . ')';
1731 $where .= $joiner if $where ne '';
1732 if ($common) { # Use a function wrapper to inform PG of the non-rareness of one or more filter elements
1734 'evergreen.query_int_wrapper(mrv.vlist, \'%s\')',
1739 'mrv.vlist @@ \'%s\'',
1745 warn "flatten(): full filter where => $where\n" if $self->QueryParser->debug;
1748 rank_list => \@rank_list,
1752 vis_filter => \%vis_filter,
1753 uses_bre => $uses_bre,
1754 uses_mrv => $uses_mrv,
1755 uses_mrd => $uses_mrd
1760 #-------------------------------
1761 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::filter;
1762 use base 'QueryParser::query_plan::filter';
1764 #-------------------------------
1765 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::facet;
1766 use base 'QueryParser::query_plan::facet';
1770 my ($classname) = split '\|', $self->name;
1776 my ($classname,@fields) = split '\|', $self->name;
1784 my $table_alias = "$self";
1785 $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
1786 $table_alias .= '_' . $self->name;
1787 $table_alias =~ s/\|/_/go;
1788 $table_alias .= "_$suffix" if ($suffix);
1790 return $table_alias;
1794 #-------------------------------
1795 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::modifier;
1796 use base 'QueryParser::query_plan::modifier';
1798 #-------------------------------
1799 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node::atom;
1800 use base 'QueryParser::query_plan::node::atom';
1806 $self->{sql} = $sql if ($sql);
1808 return $self->{sql} if ($self->{sql});
1809 return $self->buildSQL;
1815 my $classname = $self->node->classname;
1817 return $self->sql("to_tsquery('$classname','')") if $self->{dummy};
1819 my $normalizers = $self->node->plan->QueryParser->query_normalizers( $classname );
1820 my $fields = $self->node->fields;
1823 my $filter = $self->node->plan->find_filter('preferred_language');
1824 $lang ||= $filter->args->[0] if ($filter && $filter->args);
1825 $lang ||= $self->node->plan->QueryParser->default_preferred_language;
1826 my $ts_configs = [];
1829 $ts_configs = $self->node->plan->QueryParser->class_ts_config($classname, $lang);
1831 for my $field (@$fields) {
1832 push @$ts_configs, @{$self->node->plan->QueryParser->field_ts_config($classname, $field, $lang)};
1835 $ts_configs = [keys %{{map { $_ => 1 } @$ts_configs}}];
1837 # Assume we want exact if none otherwise provided.
1838 # Because we can reasonably expect this to exist
1839 $ts_configs = ['simple'] unless (scalar @$ts_configs);
1841 $fields = $self->node->plan->QueryParser->search_fields->{$classname} if (!@$fields);
1845 for my $field (@$fields) {
1846 for my $nfield (keys %$normalizers) {
1847 for my $nizer ( @{$$normalizers{$nfield}} ) {
1848 if ($field eq $nfield) {
1849 my $param_string = OpenSRF::Utils::JSON->perl2JSON($nizer->{params});
1850 if (!exists($norms{$nizer->{function}.$param_string})) {
1851 $norms{$nizer->{function}.$param_string} = {p=>$pos++,n=>$nizer};
1858 my $sql = $self->node->plan->QueryParser->quote_value($self->content);
1860 for my $n ( map { $$_{n} } sort { $$a{p} <=> $$b{p} } values %norms ) {
1861 $sql = join(', ', $sql, map { $self->node->plan->QueryParser->quote_value($_) } @{ $n->{params} });
1862 $sql = $n->{function}."($sql)";
1865 my $prefix = $self->prefix || '';
1866 my $suffix = $self->suffix || '';
1867 my $joiner = ' || ';
1868 $joiner = ' && ' if $self->prefix eq '!'; # Negative atoms should be "none of the variants" instead of "any of the variants"
1870 $prefix = "'$prefix' ||" if $prefix;
1872 my $suffix_after = '';
1874 $suffix_op = ":$suffix" if $suffix;
1875 $suffix_after = "|| '$suffix_op'" if $suffix;
1878 for my $ts_config (@$ts_configs) {
1879 push @sql_set, "to_tsquery('$ts_config', COALESCE(NULLIF($prefix '(' || btrim(regexp_replace($sql,E'(?:\\\\s+|:)','$suffix_op&','g'),'&|') $suffix_after || ')', '()'), ''))";
1882 $sql = join($joiner, @sql_set);
1883 $sql = '(' . $sql . ')' if (scalar(@$ts_configs) > 1);
1885 return $self->sql($sql);
1888 #-------------------------------
1889 package OpenILS::Application::Storage::Driver::Pg::QueryParser::query_plan::node;
1890 use base 'QueryParser::query_plan::node';
1891 use List::MoreUtils qw/uniq/;
1894 sub abstract_node_additions {
1898 my $hm = $self->plan
1901 ->get_abstract_data('highlight_map') || {};
1903 my $field_set = $self->fields;
1904 $field_set = $self->plan->QueryParser->search_fields->{$self->classname}
1907 my @field_ids = grep defined, (
1909 $self->plan->QueryParser->search_field_ids_by_class(
1910 $self->classname, $_
1915 push @field_ids, @{$self->{vfields}} if $self->{vfields};
1917 my $ts_query = $self->tsquery_rank;
1919 # We need to rework the hash so fields are only ever pointed at once.
1920 # That means if a field is already being looked at elsewhere then we'll
1921 # need to separate it out and combine its preexisting tsqueries. This
1922 # will be fairly brute-force, and could be improved later, likely, with
1923 # a clever algorithm.
1926 for my $t (keys %$hm) {
1927 for my $f (@{$$hm{$t}}) {
1928 $inverted_hm{$f} = $t;
1932 # Then, loop over new fields and put them in the inverted hash.
1933 my @existing_fields = keys %inverted_hm;
1935 for my $f (@field_ids) {
1936 if (grep { $f == $_ } @existing_fields) { # We've seen the field, should we combine?
1937 my $t = $inverted_hm{$f};
1938 if ($t ne $ts_query) { # Different tsquery, do it!
1939 $t .= ' || '. $ts_query;
1940 $inverted_hm{$f} = $t;
1942 } else { # New field
1943 $inverted_hm{$f} = $ts_query;
1947 # Now, flip it back over.
1949 for my $f (keys %inverted_hm) {
1950 my $t = $inverted_hm{$f};
1952 push @{$$hm{$t}}, $f;
1961 ->set_abstract_data('highlight_map', $hm);
1968 $self->{vfields} ||= [];
1969 push @{$self->{vfields}}, $vfield;
1975 $self->{dummy_count} = 0;
1977 my $atoms = $self->query_atoms;
1979 for my $a (@$atoms) {
1980 push(@only_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom'));
1981 $self->{dummy_count}++ if (ref($a) && $a->{dummy});
1984 return \@only_atoms;
1987 sub only_real_atoms {
1990 my $atoms = $self->query_atoms;
1991 my @only_real_atoms;
1992 for my $a (@$atoms) {
1993 push(@only_real_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}));
1996 return \@only_real_atoms;
1999 sub only_positive_atoms {
2002 my $atoms = $self->query_atoms;
2003 my @only_positive_atoms;
2004 for my $a (@$atoms) {
2005 push(@only_positive_atoms, $a) if (ref($a) && $a->isa('QueryParser::query_plan::node::atom') && !($a->{dummy}) && ($a->{prefix} ne '!'));
2008 return \@only_positive_atoms;
2013 return $self->{dummy_count};
2018 my $classname = shift || $self->classname;
2019 return 'metabib.' . $classname . '_field_entry';
2022 sub combined_table {
2024 my $classname = shift || $self->classname;
2025 return 'metabib.combined_' . $classname . '_field_entry';
2028 sub combined_search {
2030 return $self->plan->QueryParser->search_class_combined($self->classname);
2037 my $table_alias = "$self";
2038 $table_alias =~ s/^.*\(0(x[0-9a-fA-F]+)\)$/$1/go;
2039 $table_alias .= '_' . $self->requested_class;
2040 $table_alias =~ s/\|/_/go;
2041 $table_alias .= "_$suffix" if ($suffix);
2043 return $table_alias;
2048 return $self->{tsquery} if ($self->{tsquery});
2050 for my $atom (@{$self->query_atoms}) {
2052 $self->{tsquery} .= "\n" . ${spc} x 3 . $atom->sql;
2054 $self->{tsquery} .= $atom x 2;
2058 return $self->{tsquery};
2063 return $self->{tsquery_rank} if ($self->{tsquery_rank});
2066 for my $atom (@{$self->only_positive_atoms}) {
2067 push @atomlines, "\n" . ${spc} x 3 . $atom->sql;
2069 $self->{tsquery_rank} = join(' ||', @atomlines);
2070 $self->{tsquery_rank} = "''::tsquery" unless $self->{tsquery_rank};
2071 return $self->{tsquery_rank};
2076 return $self->{rank} if ($self->{rank});
2078 my $rank_norm_map = $self->plan->QueryParser->custom_data->{rank_cd_weight_map};
2080 my $cover_density = 0;
2081 for my $norm ( keys %$rank_norm_map) {
2082 $cover_density += $$rank_norm_map{$norm} if ($self->plan->QueryParser->parse_tree->find_modifier($norm));
2085 my $weights = join(', ', @{$self->plan->QueryParser->search_class_weights($self->classname)});
2087 return $self->{rank} = "ts_rank_cd('{" . $weights . "}', " . $self->table_alias . '.index_vector, ' . $self->table_alias . ".tsq_rank, $cover_density)";