Sub topic 2
Wildcards, Phrases, and Logical Operators in SOSL
Assume you know basic SOQL, Apex variables, lists, and loops. SOSL search expressions control which text matches. The RETURNING clause controls which records and fields come back.
Wildcards, phrases, and AND, OR, AND NOT
A wildcard matches additional characters. The * wildcard matches zero or more characters at the end of a term. For example, Acme* can match Acme, Acme Corp, or Acmeville.
Put multiple words in double quotes to search for an exact phrase:
FIND {"Acme Corp"} IN NAME FIELDS
RETURNING Account(Id, Name)Use logical operators to combine terms:
ANDrequires both terms.ORrequires either term.AND NOTexcludes records matching the following term.
FIND {Acme* AND NOT Test} IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, Name)Use parentheses when you need to make the grouping explicit, such as (Acme OR Globex) AND NOT Test.
Choosing objects and fields with `RETURNING`
RETURNING lists the objects to search and the fields to return. The result lists use the same order as the objects in this clause.
Filtering and ordering results per object
Each object can have its own WHERE, ORDER BY, and LIMIT. These refinements apply only to that object.
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING
Account(Id, Name
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 10),
Contact(Id, Name
WHERE Email != null
ORDER BY Name)
];Running SOSL in Apex and reading result lists
Apex stores SOSL results as List<List<SObject>>. Cast each inner list to the object type that matches its position.
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];
for (Account account : accounts) {
System.debug(account.Name);
}Exercise
If RETURNING lists Contact first and Account second, which result list contains contacts?
Show answer
results[0] contains contacts, because result-list positions follow the order of objects in RETURNING.