Sub topic 8
Running SOSL in Apex and Reading the Result Lists
This chapter covers running a SOSL query from Apex and reading the nested lists it returns. It assumes you can write a FIND clause and a RETURNING clause, and that you know Apex lists, casting, and loops. Bind variables, dynamic SOSL, and testing each get their own chapter. Here they appear only where they help explain the result shape.
Inline SOSL returns a list of lists
You write SOSL in Apex inside square brackets, the same way you write inline SOQL. A SOQL query returns one list of records. A SOSL query can search several objects, so it returns a list of lists. Each inner list holds the matches for one object.
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
];
System.debug('Outer list size: ' + results.size());
System.debug('Accounts found: ' + results[0].size());
System.debug('Contacts found: ' + results[1].size());The outer list has one entry per object named in RETURNING. The entries appear in the same order as the objects in the clause. Account is first in this query, so results[0] holds accounts and results[1] holds contacts.
The inner lists are typed as List<SObject>, so you cast them before you use object-specific fields.
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
];
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];
for (Account a : accounts) {
System.debug('Account: ' + a.Name);
}
for (Contact c : contacts) {
System.debug('Contact: ' + c.FirstName + ' ' + c.LastName);
}The cast is safe because Apex builds each inner list from the object you named at that position. If the cast fails, the usual cause is that you read the wrong index.
Empty results are empty lists
When an object has no matches, its inner list is empty, not null. The outer list still has one entry for every object in RETURNING. You can loop over any inner list without a null check, and results.size() always equals the number of objects you named.
List<List<SObject>> results = [
FIND 'zzzzNoSuchName*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id)
];
System.debug(results.size()); // 2
System.debug(results[0].isEmpty()); // trueTest emptiness with isEmpty() on the inner list you care about. Testing the outer list tells you nothing, because it is never empty when RETURNING names at least one object.
Reading results by position or by type
Reading by index is the simplest approach. It is also fragile if someone later reorders the RETURNING clause, because the casts will start failing or reading the wrong object. For queries with many objects, or with a RETURNING clause built at run time, group the records by type instead. Reading the record's own type removes the dependence on position.
public with sharing class SearchResultReader {
public static Map<String, List<SObject>> groupByType(List<List<SObject>> results) {
Map<String, List<SObject>> byType = new Map<String, List<SObject>>();
for (List<SObject> records : results) {
for (SObject record : records) {
String typeName = record.getSObjectType().getDescribe().getName();
if (!byType.containsKey(typeName)) {
byType.put(typeName, new List<SObject>());
}
byType.get(typeName).add(record);
}
}
return byType;
}
}A caller can then ask for what it needs by name and handle a missing key as "no matches":
Map<String, List<SObject>> byType = SearchResultReader.groupByType([
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, Name)
]);
List<SObject> accounts = byType.containsKey('Account')
? byType.get('Account')
: new List<SObject>();
System.debug(accounts.size());When you need to branch on type inside one loop, instanceof works too:
for (List<SObject> records : results) {
for (SObject record : records) {
if (record instanceof Account) {
Account a = (Account) record;
System.debug('Account ' + a.Name);
} else if (record instanceof Contact) {
Contact c = (Contact) record;
System.debug('Contact ' + c.Name);
}
}
}Only the fields you listed are populated
SOSL returns the fields named in each RETURNING entry, plus the Id. If you read any other field, Apex throws a System.SObjectException that says the row was retrieved via SOSL without querying the field. The same rule applies to inline SOQL.
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name)
];
Account a = (Account) results[0][0];
System.debug(a.Name); // works
System.debug(a.Industry); // throws System.SObjectExceptionAdd the field to the RETURNING entry, for example Account(Id, Name, Industry). If you list an object with no fields, as in RETURNING Account, you get only the Id.
Order of records inside each list
Without an ORDER BY in the RETURNING entry, each inner list is sorted by search relevance, and the order is not guaranteed to be stable across runs. Do not treat results[0][0] as the "best" account in any sense you rely on for business logic. If the order matters, add ORDER BY to that object's entry, as covered in the per-object filtering chapter.
Working with the records you found
The inner lists are ordinary lists of sObjects. You can pass them to a map constructor, update them, or collect their Ids:
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, AccountId)
];
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];
Map<Id, Account> accountsById = new Map<Id, Account>(accounts);
Set<Id> contactAccountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
contactAccountIds.add(c.AccountId);
}
}
System.debug('Matched accounts: ' + accountsById.size());
System.debug('Accounts referenced by matched contacts: ' + contactAccountIds.size());Records returned by SOSL can be updated or deleted like any queried records. Fields you did not list in RETURNING are not loaded, so a record you want to update only needs the Id plus the fields you change.
Search term rules that surface as runtime errors
A static query with a literal term is checked when the class compiles. A term supplied at run time is not, so these failures appear only when the code runs:
- A search term must have at least two characters, not counting wildcards. A single character raises a
System.QueryException. Check the length of user input before you run the query. - A bind variable that is null raises an error. Guard against a null or blank term first.
- A RETURNING object that is not searchable fails the query.
public with sharing class SafeSearch {
public static List<Account> search(String term) {
if (String.isBlank(term) || term.trim().length() < 2) {
return new List<Account>();
}
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name LIMIT 20)
];
return (List<Account>) results[0];
}
}Limits and sharing that affect the result
Two limits shape how you structure SOSL code in a transaction:
- A transaction can run up to 20 SOSL queries.
- Each SOSL query returns at most 2,000 records in total across all the inner lists.
Those 2,000 records are shared among the objects in RETURNING. If the first object fills the quota, the others can come back empty even though they have matches. Put a LIMIT on each object so the quota is split the way you intend. Do not run a SOSL query inside a loop. Run one query per transaction step and read its lists.
Sharing follows the class. A class declared with sharing returns only the records the running user can see. Field-level access is a separate matter, and the security chapter covers how to enforce it.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Assuming `results[0]` is always the first object you care about | Wrong cast or wrong records after RETURNING is reordered | Group by type, or keep the index tied to a documented order |
| Checking `results == null` | The check never helps, because the outer list is never null | Check `isEmpty()` on the inner list |
| Reading a field not in RETURNING | `System.SObjectException` | Add the field to that object's entry |
| One-character search term | `System.QueryException` | Validate the term length first |
| Several large objects with no per-object LIMIT | One object uses the whole 2,000-record quota | Add a LIMIT to each RETURNING entry |
Exercise
A query is FIND 'Globex*' IN ALL FIELDS RETURNING Contact(Id, Name), Lead(Id, Company), Account(Id, Name). No record matches the term. What are the outer list size and the size of results[2], and which expression would raise an exception, results[1][0] or results[1].isEmpty()?
Show answer
The outer list size is 3, because it has one entry per object in RETURNING. results[2] is the Account list and its size is 0, because an object with no matches gives an empty list, not null. results[1][0] raises a System.ListException because the Lead list is empty and has no element at index 0. results[1].isEmpty() is safe and returns true.