0

I'm running a SOSL query in my Apex code using Search.query. My existing query with one term already works.

This

String queryString = 'FIND \'' + guid + '\' IN ALL FIELDS RETURNING Opportunity(My_Field__c)';

Executes as this

FIND '5559da13-afd7-4bd5-ae65-cd31dd439596' IN ALL FIELDS RETURNING Opportunity(My_Field__c)

However, I now want to add another term with an OR condition. From the Query Editor in the Developer Console I can do this by wrapping the two terms, separated by OR with brackets ( { and }). So the following works from Developer Console.

FIND {5559da13\-afd7\-4bd5\-ae65\-cd31dd439596 or abc124} IN ALL FIELDS RETURNING Opportunity(My_Field__c)

Although from Developer Console I don't put single quote around the values which Search.query seems to require.

So the result is trying to pass the following to Search.query.

FIND {'5559da13-afd7-4bd5-ae65-cd31dd439596' or 'abc123'} IN ALL FIELDS RETURNING Opportunity(My_Field__c)

The result is an exception:

System.QueryException: expecting a string literal, found '{'

So my question is how do I format my search string to include the second condition to pass to Search.query? The Search.query function doesn't seem to accept the OR and brackets like the Developer Console Query Editor does.

1 Answer 1

3

For some undocumented reason, they decided to make SOSL in Apex slightly different than what's in the SOSL documentation. Instead of using {}, you use ''. In other words, your Apex code would look like:

String searchQuery = 'FIND \'\\\'5559da13\\\\-afd7\\\\-4bd5\\\\-ae65\\\\-cd31dd439596\\\'' +
  ' or \\\'abc124\\\'\' IN ALL FIELDS '+
  'RETURNING Opportunity(My_Field__c)';

You use \' to escape a literal quote, \\ to escape a literal backslash, and thus \\\' to escape a single quote as seen by SOSL, and \\\\- to escape a hyphen character.

2
  • @sfdxfox wow, that's a lot of slashes and single quotes. :) For my situation the search values are variables so lots of escape. I actually found another answer after trying different search terms in Google. The actual solution I used was actually answered by you as well. String queryString = 'FIND \'' + guid+ ' or ' + altId + '\' IN ALL FIELDS RETURNING Opportunity(My_Field__c)'; salesforce.stackexchange.com/questions/257735/…
    – James
    Sep 21, 2023 at 21:19
  • Note that this apex expression in FIND works [FIND '"abc" or "def"' IN ALL FIELDS RETURNING Account(id, name)]; But same expression does not work in Search.query (or at least I couldn't figure out how)
    – cropredy
    Sep 21, 2023 at 21:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .