Your First SOSL Search
By the end of this lesson, you'll be able to:
- Write a basic SOSL search using FIND and RETURNING
- Run a SOSL search in Apex and read the result structure
- Explain what a List<List<sObject>> represents in this context
Prerequisites: "What Is SOSL?"
The basic shape
List<List<sObject>> searchResults = [
FIND 'Riverbend Farms' IN ALL FIELDS
RETURNING Account(Id, Name)
];
List<Account> matchingAccounts = searchResults[0];
System.debug(matchingAccounts.size());
FIND 'Riverbend Farms' names the search text; IN ALL FIELDS means search every searchable text field; RETURNING Account(Id, Name) names which fields to return for matching Account records.
Why a List of Lists
List<List<sObject>> searchResults = [
FIND 'Riverbend Farms' IN ALL FIELDS
RETURNING Account(Id, Name), Contact(Id, LastName)
];
List<Account> accounts = searchResults[0]; // matches from Account
List<Contact> contacts = searchResults[1]; // matches from Contact
This is exactly Module 16's "Nested Collections" pattern applied to search results: the outer List has one entry per object named in RETURNING, in the same order they were listed, and each inner List<sObject> holds that object type's matches — searchResults[0] for the first object named, searchResults[1] for the second, and so on.
sObject typing on the inner Lists
List<Account> matchingAccounts = (List<Account>) searchResults[0];
Depending on how the result is used, you may need to cast the inner List<sObject> to its specific type — this is Module 18's sObject polymorphism concept (a specific type can be cast back down from the generic base type) showing up directly in a real SOSL result.
Exercise
Write a SOSL search for 'Acme' returning Id and Name from Account, and debug the number of matches found.
Show hint
FIND 'Acme' IN ALL FIELDS RETURNING Account(Id, Name)
Your First SOSL Search Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A basic SOSL search names the text to find and which object(s) to return matches from — in Apex, the result comes back as a List of Lists, one inner List per object type searched.