Search names with SOSL
SOQL queries · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A support rep types part of a name into one search box. They expect matching companies first, then matching people, each in A to Z order.
Run one SOSL search across Accounts and Contacts, return the names in a set order, and see why tests need Test.setFixedSearchResults.
What you will learn
SOSL searches text in several objects at once. It returns one list per object, in the order after RETURNING.
List<List<SObject>> hits = [
FIND :term IN NAME FIELDS
RETURNING Account(Name), Contact(LastName)
];
Gotcha. SOSL matches whole words. 'Harbor' finds Harbor Alpha, not Harborview. Add trailing * for prefix search; leading * is rejected.
Gotcha. SOSL uses an index that lags saves. Tests find nothing until Test.setFixedSearchResults(ids).
The task
Complete findNames so one SOSL search returns the names of matching Accounts, then the last names of matching Contacts.
Examples:
findNames('Harbor')finds AccountsHarbor BetaandHarbor Alphaand a Contact named Maya Harbor →(Harbor Alpha, Harbor Beta, Harbor)findNames('Nobody')finds nothing → an empty listfindNames(null),findNames(' ')orfindNames(' H ')→ an empty list, and no search runs
Requirements:
- SOSL needs at least 2 characters. If
termis null, blank, or shorter than 2 characters after you trim the spaces, return an empty list (not null) without searching. - Run one SOSL search for the trimmed term
IN NAME FIELDS, returning AccountNameand ContactLastName. - Sort each object A to Z with
ORDER BYinside its part ofRETURNING. - Add every Account
Namefirst, then every ContactLastName, and return the list.
Starter code
public class AS_6C2F11FEB11B_NameSearch {
public static List<String> findNames(String term) {
List<String> names = new List<String>();
return names;
}
}
When it passes
One SOSL search returns Account names A to Z, then Contact last names A to Z. A missing, blank or 1-character term returns an empty list without searching, and a search with no hits returns an empty list.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.