Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

properly quote for solr

  • Loading branch information...
commit e6e8322ac41e1a4d592eb9982b1a832842fdec4e 1 parent c785887
@jrochkind authored
Showing with 24 additions and 7 deletions.
  1. +18 −7 lib/cql_ruby/cql_to_solr.rb
  2. +6 −0 test/test_cql_to_solr.rb
View
25 lib/cql_ruby/cql_to_solr.rb
@@ -116,19 +116,19 @@ def to_solr
# match/exclude on partial matches too, not only complete matches.
when "<>"
negate = true
- maybe_quote(@term)
- when "cql.adj", "==" then maybe_quote(@term)
+ solr_maybe_quote(@term)
+ when "cql.adj", "==" then solr_maybe_quote(@term)
when "cql.all" then '(' + @term.split(/\s/).collect{|a| '+'+a}.join(" ") + ')'
when "cql.any" then '(' + @term.split(/\s/).join(" OR ") + ')'
- when ">=" then "[" + maybe_quote(@term) + " TO *]"
- when ">" then "{" + maybe_quote(@term) + " TO *}"
- when "<=" then "[* TO " + maybe_quote(@term) + "]"
- when "<" then "{* TO " + maybe_quote(@term) + "}"
+ when ">=" then "[" + solr_maybe_quote(@term) + " TO *]"
+ when ">" then "{" + solr_maybe_quote(@term) + " TO *}"
+ when "<=" then "[* TO " + solr_maybe_quote(@term) + "]"
+ when "<" then "{* TO " + solr_maybe_quote(@term) + "}"
when "cql.within"
bounds = @term.gsub('"', "").split(/\s/)
raise CqlException.new("can not extract two bounding values from within relation term: #{@term}") unless bounds.length == 2
- "[" + maybe_quote(bounds[0]) + " TO " + maybe_quote(bounds[1]) + "]"
+ "[" + solr_maybe_quote(bounds[0]) + " TO " + solr_maybe_quote(bounds[1]) + "]"
else
raise CqlException.new("relation not supported: #{relation}")
end
@@ -140,6 +140,17 @@ def to_solr
return ret
end
+
+ # utility method, quotes/escapes value, if needed, for inclusion
+ # in solr lucene query parser term.
+ # wraps in double quotes if needed, backslash-escapes internal double
+ # quotes.
+ def solr_maybe_quote(term)
+ return term unless term =~ /[^a-zA-Z0-9_]/
+
+ return '"' + term.gsub('"', '\\"') + '"'
+ end
+
end
class CqlBooleanNode
View
6 test/test_cql_to_solr.rb
@@ -89,6 +89,12 @@ def test_all_index
assert_to_solr_eq("cql.allindexes = val", @@parser.parse("my_all_index = val").to_solr)
end
end
+
+ def test_escapes_terms
+ assert_to_solr_eq('text = ab[]cd', 'text:"ab[]cd"')
+
+ assert_to_solr_eq('text = "one\'s \" two"', 'text:"one\'s \" two"')
+ end
#############
# Helpers
Please sign in to comment.
Something went wrong with that request. Please try again.