Intermediate
20 min read
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());
List<List<sObject>> searchResults = [— opens the search, stored as a list of lists.FIND 'Riverbend Farms' IN ALL FIELDS—FINDnames the search text;IN ALL FIELDSmeans search every searchable text field.RETURNING Account(Id, Name)— names which fields to return for matchingAccountrecords.];— closes the search.- (blank line)
List<Account> matchingAccounts = searchResults[0];— the first (and only) inner list, holding theAccountmatches.System.debug(matchingAccounts.size());— logs how many matched.
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
List<List<sObject>> searchResults = [— this is exactly Module 16's "Nested Collections" pattern applied to search results.FIND 'Riverbend Farms' IN ALL FIELDS— the search text and scope.RETURNING Account(Id, Name), Contact(Id, LastName)— now two object types named, in this order.];— closes the search.- (blank line)
List<Account> accounts = searchResults[0];— the outerListhas one entry per object named inRETURNING, in the same order — index0for the first object named.List<Contact> contacts = searchResults[1];— index1for the second.
sObject typing on the inner Lists
List<Account> matchingAccounts = (List<Account>) searchResults[0];
List<Account> matchingAccounts = (List<Account>) searchResults[0];— depending on how the result is used, the innerList<sObject>may need casting to its specific type — this is Module 18'ssObjectpolymorphism 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.