Escaping reserverved characters in SOSL queries

Escaping reserverved characters with backslash as described in Force documentation (http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_sosl_find.htm) give unexpected results:

  1. Using syntax with quotes (FIND ‘*company\\?*’ IN ALL FIELDS RETURNING …) I am getting errors like “Invalid string literal ‘company\?‘. Illegal character sequence ‘\?’ in string literal.”
  2. Using syntax with braces (FIND {*company\\?*} IN ALL FIELDS RETURNING …) I am getting empty result, which is actually wrong result

Updated. Tried 4 backslashes, result – empty list:

String soslQuery = 'FIND \'worldwide company\\\\?\' IN NAME FIELDS RETURNING Account(ID, NAME)';
List<List<SObject>> searchList = Search.query(soslQuery);
for(Account account : (List<Account>)searchList[0])
{
    System.debug(account.name);
}

Answer

Since you are using single quotes around your search term, I assume you are running this in apex inside of square brackets, like so:

list<list<sobject>> results = [find '*company\\?' in all fields returning contact (id, name)];

I also assume you are trying to search for a literal “?” in your result. It isn’t intuitive, but it appears that Apex processes the string once, and then the SOSL engine processes it again. So you’ll need to re-double your backslashes, like so:

list<list<string>> results = [find '*company\\\\?' in all fields returning contact (id, name)];

If you look at the apex log for my version, you’ll see this:

SOSL_EXECUTE_BEGIN [1]|FIND '*company\\?' IN all FIELDS RETURNING contact(id,name)

Here it has changed each pair of backslashes into single backslash; I believe they are being converted to a single backslash by the SOSL engine.

Attribution
Source : Link , Question Author : dika90 , Answer Author : Jason Clark

Leave a Comment