Sub topic 6
Choosing objects and fields with RETURNING
This chapter assumes you can write a basic FIND clause, know SOQL field lists, and can run anonymous Apex. It covers what the RETURNING clause controls, how its order maps to the result lists, and the errors that most often come up.
What RETURNING does
The FIND clause decides which text to look for. The RETURNING clause decides what comes back. It names the objects you want records from and, for each one, the fields to load.
FIND {Acme} IN ALL FIELDS
RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)Each entry has the form ObjectName(field list). The field list works like the SELECT list in SOQL, but you write it in parentheses after the object name.
If you leave RETURNING out, the search covers all searchable objects. In that case the response contains only the record Id and the object type. Because you cannot control the fields or the objects, most Apex code names RETURNING explicitly.
Field lists
Each object in RETURNING can have its own field list.
Account(Id, Name, Industry)returns those three fields.Accountwith no parentheses returns only theId.Contact(Id, Account.Name)can read fields through a parent relationship, as in SOQL.Contact(Id, Name)is valid.Nameon Contact is a compound field.
Only the fields you list are populated. Reading any other field on a returned record throws System.SObjectException: SObject row was retrieved via SOQL without querying the requested field. The message says SOQL, but the same rule applies to SOSL results.
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)
];
List<Account> accounts = (List<Account>) results[0];
Account first = accounts.isEmpty() ? null : accounts[0];
if (first != null) {
System.debug(first.Name); // works, Name was listed
// System.debug(first.Industry); // would throw SObjectException
}RETURNING order decides the result order
A SOSL query in Apex returns a List<List<SObject>>. The outer list has one inner list for each object in RETURNING, in the same order you wrote them. The first object is at index 0, the second at index 1, and so on.
An inner list is empty when nothing matched for that object. It is never null. That makes loops safe without a null check.
Because the mapping depends only on position, reordering the RETURNING clause silently changes which cast is correct. If you move Contact in front of Account, (List<Account>) results[0] fails at run time with a System.TypeException. When the order matters to your code, add a comment next to the query. You can also read the result by type rather than by position:
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, Name)
];
List<Account> accounts = new List<Account>();
List<Contact> contacts = new List<Contact>();
for (List<SObject> group : results) {
for (SObject record : group) {
if (record instanceof Account) {
accounts.add((Account) record);
} else if (record instanceof Contact) {
contacts.add((Contact) record);
}
}
}
System.debug(accounts.size() + ' accounts, ' + contacts.size() + ' contacts');This is slightly longer than casting by index, but it keeps working if someone reorders the clause.
Per-object clauses
Inside the parentheses, you can add WHERE, ORDER BY, LIMIT and OFFSET after the field list. They apply only to that object.
String term = 'Acme';
List<List<SObject>> results = [
FIND :term IN ALL FIELDS
RETURNING
Account(Id, Name WHERE Industry = 'Technology' ORDER BY Name LIMIT 10),
Contact(Id, Name WHERE Email != null)
];Here the Account list is filtered to Technology accounts, sorted by name, and capped at 10. The Contact list is filtered by email only and has no limit of its own. The next chapter covers these clauses in detail. For now, the point is that each object is configured independently.
Which objects you can name
RETURNING accepts standard and custom objects that support search. Some objects cannot be searched at all, and naming one gives a compile-time or run-time error. Check the object's isSearchable() value in its describe result if you build the list from user input or configuration.
Schema.DescribeSObjectResult describe = Account.SObjectType.getDescribe();
System.debug('Account searchable: ' + describe.isSearchable());Two more points about object access:
- If the running user cannot see an object, SOSL returns no records for it. It does not raise an error by default.
- Objects named in RETURNING must also be allowed by the search scope. A scope such as
IN EMAIL FIELDSonly matches objects that have email fields, so objects without them contribute nothing.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `SObjectException` when reading a field | The field is missing from the RETURNING field list | Add the field to the list |
| `TypeException` on a cast | The cast index does not match the RETURNING order | Match the index to the order, or branch with `instanceof` |
| Result list is empty for an object | Search term is not in the chosen scope, or the user lacks access | Widen the scope or check sharing and field access |
| Query fails to compile | Misspelled object or field name, or an unsearchable object | Check names and `isSearchable()` |
| Newly inserted record not found | The search index updates asynchronously | Use `Test.setFixedSearchResults` in tests, and allow for indexing delay in real use |
Keeping result sizes under control
Each SOSL query returns up to 2,000 records in total across all objects, and a per-object LIMIT helps share that budget. Without it, a common object such as Contact can crowd out others. Setting limits like Account(Id, Name LIMIT 20) and Contact(Id, Name LIMIT 20) gives you a predictable result shape.
Putting it together
The method below searches three objects, limits each, and returns a map from object name to record Ids. It reads results by type, so it does not depend on RETURNING order.
public with sharing class MultiObjectSearch {
public static Map<String, List<Id>> idsByObject(String term) {
Map<String, List<Id>> output = new Map<String, List<Id>>();
List<List<SObject>> results = [
FIND :term IN ALL FIELDS
RETURNING
Account(Id LIMIT 20),
Contact(Id LIMIT 20),
Opportunity(Id LIMIT 20)
];
for (List<SObject> group : results) {
for (SObject record : group) {
String typeName = record.getSObjectType().getDescribe().getName();
if (!output.containsKey(typeName)) {
output.put(typeName, new List<Id>());
}
output.get(typeName).add(record.Id);
}
}
return output;
}
}Exercise
A query reads RETURNING Contact(Id, Name), Account(Id, Name). Your code runs List<Account> a = (List<Account>) results[0]; and fails at run time. What is wrong, and what are two ways to fix it?
Show answer
Contact is listed first, so results[0] holds contacts and the cast to List<Account> throws a TypeException. Fix it by using results[1] for accounts, or by reordering RETURNING to put Account first. A sturdier option is to loop over all inner lists and sort records by type with instanceof.
Exercise
You search with RETURNING Account(Id, Name) and then read acc.Industry on a result. What happens, and how do you correct it?
Show answer
Apex throws an SObjectException because Industry was not in the field list. Add Industry to the list: Account(Id, Name, Industry).