Escaping Characters in a Solr Query / Solr URL
We’re using our own Solr library at Derdubor at the moment, but we’ve only been using it for indexing content. The query part was never standardized in our common library as we usually used an alternative output format, but during the last days that has changed. We now have a parser for the default XML outputter and we’re also supporting facets and field queries (or constraints as they’re abstracted as in our library).
This means that we’re feeding content into the query that may contain foreign characters, in particular those who have special meaning in a Solr query. You can find the complete list of characters that need to be escaped in a SOLR or Lucene query in the Lucene manual.
To escape the characters we use this very simple and stupid PHP method:
-
static public function escapeSolrValue($string)
-
{
-
$match = array('\\', '+', '-', '&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '"', ';', ' ');
-
$replace = array('\\\\', '\\+', '\\-', '\\&', '\\|', '\\!', '\\(', '\\)', '\\{', '\\}', '\\[', '\\]', '\\^', '\\~', '\\*', '\\?', '\\:', '\\"', '\\;', '\\ ');
-
$string = str_replace($match, $replace, $string);
-
-
return $string;
-
}
We used a regular expression first, but the sheer amount of backslashes made it a regular .. hell … to read. So to make it easier for the persons maintaining this in the future, we went the easy to read / easy to maintain road for this one.
Tags: Apache, escaping, PHP, Solr, str_replace


January 22nd, 2010 at 22:04
You can verify this function against Solr’s Java client ClientUtils.escapeQueryChars. See http://svn.apache.org/repos/asf/lucene/solr/trunk/src/solrj/org/apache/solr/client/solrj/util/ClientUtils.java
January 23rd, 2010 at 23:44
Good point. I’ve used SolrJ quite a bit before, but I never thought about validating it against the same behaviour. SolrJ also escapes ” and ; which were missing from my list. I’ve added them now.
Thanks for the update!
January 30th, 2010 at 23:24
[...] up on the previous post about escaping values in a Solr query string, it’s important to note that you should not escape spaces in the query itself. The reason for [...]