0

I have a list of strings (phones) which I'm trying to use inside my SOSL Find clause and its giving me issues:

List<String> phonesList = new List<String>();
for(Account acc : acclist) {
        phonesList.add(acc.Phone);
}
System.debug(phonesList.size());
System.debug(phonesList[0]);

Until this point I can see the string, let's call it: 1112223333

When I try to use the phonesList[] inside a SOSL like this one:

List<List<SObject>> searchList = [FIND :phonesList IN PHONE FIELDS Returning Account(Id, Name)];

I'm getting the next error in Execute Anonymous:

Specified search expression can not be converted to string

The Anonymous error line refers to the SOSL line.

Thank you for your help.

3
  • From the docs, "A search query includes the literal word or phrase and can also include wildcards and logical operators (AND, OR, and AND NOT)".
    – TSmith
    Oct 8, 2021 at 16:13
  • Thank you, I saw the docs but it still fails. If I set only one string in the FIND {term} it works, but not the bind, although there are examples of binding: developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…
    – BoDiE2003
    Oct 8, 2021 at 16:32
  • the binding examples for collections you cite apply to SOQL; you'll need your bind variable to look like val1 OR val2 OR val3 ...
    – cropredy
    Oct 8, 2021 at 16:52

1 Answer 1

1

The only way I can think of achieving this with SOSL is to pre-build the searchQuery as if it was using the OR operator.

You will need to do some cleansing before you start building the searchQuery, additional characters may need to be substituted depending on your data. If not complete, I expect you to receive an exception along the lines of System.QueryException: line x:xx mismatched character ....

List<String> phonesList = new List<String>();
for(Account acc : acclist) {
    phonesList.add(acc.Phone.replace('-', ' ').replace('+', ' '));
}

Now it's time to work through your phonesList and start building the searchQuery. You may wish to tidy this logic up with another loop variation. We are expecting a result like numberOne OR numberTwo OR numberXX.

String concatenatedNumbers = '';

for (Integer i=0; i<=phonesList.size()-1; i++) {
    if (i == phonesList.size() - 1) {
        concatenatedNumbers = concatenatedNumbers + ' OR ' + phonesList[i];
    } else if (String.isEmpty(concatenatedNumbers)) {
        concatenatedNumbers = phonesList[i];
    } else {
        concatenatedNumbers = concatenatedNumbers + ' OR ' + phonesList[i] + ' ';
    }
}

And then we put it all to action. The search system class allows us to call a dynamic SOSL using query().

String query = 'FIND {' + concatenatedNumbers + '} IN PHONE FIELDS Returning Account(Id, Name)';
List<List<SObject>> searchList = search.query(query);

You must log in to answer this question.

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