1 package Koha::SearchEngine::Solr::QueryBuilder;
6 with 'Koha::SearchEngine::QueryBuilderRole';
8 sub build_advanced_query {
9 my ($class, $indexes, $operands, $operators) = @_;
15 @$operands or return "*:*"; #push @$operands, "[* TO *]";
18 for my $kw (@$operands){
19 $kw =~ s/(\w*\*)/\L$1\E/g; # Lower case on words with right truncation
20 $kw =~ s/(\s*\w*\?+\w*\s*)/\L$1\E/g; # Lower case on words contain wildcard ?
21 $kw =~ s/([^\\]):/$1\\:/g; # escape colons if not already escaped
24 if ( (my @x = eval {@$indexes} ) == 0 ){
25 # There is no index, then query is in first operand
30 # Catch index name if it's not 'all_fields'
31 if ( @$indexes[$i] ne 'all_fields' ) {
32 $index_name = @$indexes[$i];
37 # Generate index:operand
38 $q .= BuildTokenString($index_name, $kw);
44 $index_name = @$indexes[$i] if @$indexes[$i];
45 my $operator = defined @$operators[$i-1] ? @$operators[$i-1] : 'AND';
46 for ( uc ( $operator ) ) {
48 $q .= BuildTokenString($index_name, $kw, 'OR');
51 $q .= BuildTokenString($index_name, $kw, 'NOT');
54 $q .= BuildTokenString($index_name, $kw, 'AND');
64 sub BuildTokenString {
65 my ($index, $string, $operator) = @_;
68 if ($index ne 'all_fields' && $index ne ''){
69 # Operand can contains an expression in brackets
72 and not ( $string =~ /^\(.*\)$/ )
73 and not $string =~ /\[.*TO.*\]/ ) {
74 my @dqs; #double-quoted string
75 while ( $string =~ /"(?:[^"\\]++|\\.)*+"/g ) {
77 $string =~ s/\ *\Q$&\E\ *//; # Remove useless space before and after
80 my @words = defined $string ? split ' ', $string : undef;
81 my $join = join qq{ AND } , map {
83 if ( $index =~ /^date_/ ) {
84 #$value = C4::Search::Engine::Solr::buildDateOperand( $value ); TODO
86 ( $value =~ /^"/ and $value ne '""'
87 and $index ne "emallfields"
88 and $index =~ /(txt_|ste_)/ )
94 if ( $index =~ /^date_/ ) {
95 #$string = C4::Search::Engine::Solr::buildDateOperand( $string ); TODO
98 $r = "$index:$string";
104 return " $operator $r" if $operator;
109 my ($class, $query) = @_;
111 return "*:*" if not defined $query;
113 # Particular *:* query
114 if ($query eq '*:*'){
118 $query =~ s/(\w*\*)/\L$1\E/g; # Lower case on words with right truncation
119 $query =~ s/(\s*\w*\?+\w*\s*)/\L$1\E/g; # Lower case on words contain wildcard ?
121 my @quotes; # Process colons in quotes
122 while ( $query =~ /'(?:[^'\\]++|\\.)*+'/g ) {
127 my $replacement = $_;
128 $replacement =~ s/[^\\]\K:/\\:/g;
129 $query =~ s/$_/$replacement/;
132 $query =~ s/ : / \\: /g; # escape colons if " : "
134 my $new_query = $query;#C4::Search::Query::splitToken($query); TODO
136 $new_query =~ s/all_fields://g;
138 # Upper case for operators
139 $new_query =~ s/ or / OR /g;
140 $new_query =~ s/ and / AND /g;
141 $new_query =~ s/ not / NOT /g;