Sub topic 7
Filtering and ordering results per object
This chapter assumes you can write a basic FIND query with a RETURNING clause, as covered earlier in this tutorial. You should also know SOQL WHERE, ORDER BY, and LIMIT, and how to read the List<List<SObject>> result in Apex.
A SOSL query can search many objects at once. A single query often needs different rules for each object. You might want only technology accounts, contacts that have an email address, and open opportunities. This chapter shows how to attach those rules to each object inside RETURNING.
Where per-object clauses go
Each object in RETURNING takes a parenthesized list. The list starts with the fields to return. After the fields you can add optional clauses, in this order:
WHEREfilters the matching records.ORDER BYsorts them.LIMITcaps how many come back.OFFSETskips records, which is useful for paging.
FIND {Acme}
IN NAME FIELDS
RETURNING
Account(Id, Name WHERE Industry = 'Technology' ORDER BY Name LIMIT 10),
Contact(Id, Name WHERE Email != null ORDER BY LastName)There are no commas between the clauses. The clauses follow the last field name, separated by spaces. A comma there is a syntax error.
The clauses belong to one object only. The WHERE on Account has no effect on Contact. An object listed with no extra clauses is returned unfiltered, up to the default limit.
Filtering with WHERE
The WHERE clause uses the same syntax as SOQL. You can use comparison operators, IN, LIKE, AND, OR, NOT, date literals, and bind variables.
The text search decides which records match the term. WHERE then narrows those matches by field values. A record must satisfy both to appear.
The fields in WHERE do not have to be in the field list. This query filters on Industry but returns only Id and Name:
String term = 'Acme';
String industry = 'Technology';
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING
Account(Id, Name WHERE Industry = :industry),
Contact(Id, Name WHERE Email != null AND Account.Industry = :industry)
];
List<Account> accounts = (List<Account>) results[0];
List<Contact> contacts = (List<Contact>) results[1];
System.debug(accounts.size() + ' accounts, ' + contacts.size() + ' contacts');Note two details here:
- The bind variable
:industryworks inside the per-objectWHERE, so you can pass user input safely without building a string. - The Contact filter reaches through the relationship to
Account.Industry. This lets one query apply a parent-record rule to a child object.
If you change the FIND term, the WHERE clauses keep working unchanged. This makes the pattern easy to reuse in a method that takes the search term as a parameter.
Ordering with ORDER BY
Without ORDER BY, SOSL returns each object's records in relevance order. Relevance is the index's estimate of how well a record matches the term. The order is not guaranteed to be stable between runs, and it is not alphabetical.
Add ORDER BY when the user expects a predictable order, such as a list sorted by name or by amount.
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING
Account(Id, Name, AnnualRevenue ORDER BY AnnualRevenue DESC NULLS LAST),
Opportunity(Id, Name, Amount WHERE IsClosed = false ORDER BY Amount DESC NULLS LAST)
];You can sort by more than one field, such as ORDER BY LastName ASC, FirstName ASC. ASC is the default direction. Add NULLS FIRST or NULLS LAST when empty values should go to a known end of the list.
Each object is sorted on its own. There is no way to sort Accounts and Contacts together into one list, because they come back as separate lists. If you need a combined, sorted list, merge the lists in Apex and sort them there.
Capping results with LIMIT
LIMIT inside an object's parentheses caps that object only. This is how you keep one common object from filling the result.
List<List<SObject>> results = [
FIND 'Smith' IN NAME FIELDS
RETURNING
Contact(Id, Name ORDER BY LastName LIMIT 5),
Lead(Id, Name ORDER BY LastName LIMIT 5)
];When ORDER BY and LIMIT are used together, the sort is applied first. You get the first five records in sort order, not five arbitrary records that are then sorted.
SOSL has two other limits that interact with this one:
| Limit | Where it applies | Notes |
|---|---|---|
| Per-object `LIMIT n` | Inside the object's parentheses | Caps that one object's list. |
| Query-level `LIMIT n` | After the whole RETURNING clause | Caps the total number of records across all objects. |
| Default cap | When you write no `LIMIT` | Up to 2,000 records are returned for the query. |
If you write no LIMIT anywhere, an Apex SOSL query can return up to 2,000 records. That is a lot of heap for a search box. Always set a LIMIT that matches what the user interface can display.
Paging with OFFSET
OFFSET skips a number of records before the results start. Combine it with LIMIT and ORDER BY to build pages.
Integer pageSize = 10;
Integer pageNumber = 2; // pages start at 1
Integer skip = (pageNumber - 1) * pageSize;
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING
Account(Id, Name ORDER BY Name, Id LIMIT :pageSize OFFSET :skip)
];
List<Account> page = (List<Account>) results[0];Keep these points in mind:
- Always include
ORDER BYwhen you useOFFSET. Without it, relevance order can shift between calls, and a record can appear on two pages or on none. - Add
Idas a final sort field. Two accounts with the same name would otherwise have no fixed order between them. - Paging in SOSL is shallow. Total results are capped at 2,000, so you cannot page through an unlimited result set. For deep paging over large data, SOQL is the better tool.
Fields, filters, and what is searched
Per-object clauses do not change where the text is searched. The search scope (IN NAME FIELDS, IN ALL FIELDS, and so on) decides which fields are matched against the term. WHERE only filters by field values after the match.
For example, FIND 'Acme' IN NAME FIELDS with Account(Id WHERE Industry = 'Technology') matches the word in the account name. It does not search the Industry text for 'Acme'.
Objects that are not named in RETURNING are not searched at all. If you want a Contact and an Account search, both must appear in the clause.
An object listed with no field list, such as Account, returns only Id. If you add WHERE you must still list at least one field first, as in Account(Id WHERE ...).
A reusable pattern
A common structure for a search method keeps the filters in one place and takes its inputs as bind variables. The code below runs as anonymous Apex.
public with sharing class CustomerSearch {
public static Map<String, List<SObject>> search(
String term, String industry, Integer pageSize, Integer skip
) {
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING
Account(Id, Name, Industry
WHERE Industry = :industry
ORDER BY Name, Id
LIMIT :pageSize OFFSET :skip),
Contact(Id, Name, Email
WHERE Email != null
ORDER BY LastName, Id
LIMIT :pageSize)
];
return new Map<String, List<SObject>>{
'accounts' => results[0],
'contacts' => results[1]
};
}
}The method returns a map keyed by name. Callers then do not depend on the position of each object in RETURNING. If someone later reorders the clause, only this method changes.
Common errors
- A comma before
WHERE. WritingAccount(Id, Name, WHERE ...)is a syntax error. Remove the comma after the last field. - Clauses in the wrong order.
LIMITbeforeORDER BYfails to compile. Use the order WHERE, ORDER BY, LIMIT, OFFSET. - Expecting a combined sort.
ORDER BYsorts each object's list separately. - Paging without a sort.
OFFSETwith noORDER BYgives unstable pages. - Casting the wrong index.
results[1]is the second object in RETURNING. Casting it to the wrong type throws aTypeException.
Exercise
A search page shows up to 5 open opportunities and up to 5 contacts that have an email address, for the term in a variable named term, searched in name fields. Opportunities should be sorted by Amount from largest to smallest, with empty amounts last. Contacts should be sorted by last name. Write the static SOSL query in Apex and say why the sort and the limit are written inside the parentheses.
Show answer
List<List<SObject>> results = [ FIND :term IN NAME FIELDS RETURNING Opportunity(Id, Name, Amount WHERE IsClosed = false ORDER BY Amount DESC NULLS LAST LIMIT 5), Contact(Id, Name, Email WHERE Email != null ORDER BY LastName LIMIT 5) ]; The clauses are inside each object's parentheses because they apply to that object only. A sort or limit there does not affect the other object, and each result list is sorted and capped on its own. A single query-level LIMIT would cap the total across both objects instead.
Exercise
A developer pages through account results with Account(Id, Name LIMIT 10 OFFSET :skip). Users report that some accounts show up on two pages and others never show up. What is wrong, and what is the fix?
Show answer
There is no ORDER BY, so the records come back in relevance order, which can change between calls. Add a fixed sort with a unique tie-breaker, for example Account(Id, Name ORDER BY Name, Id LIMIT 10 OFFSET :skip). Remember that SOSL caps total results at 2,000, so paging only works for shallow result sets.