Sub topic 4
Choosing where to search with search groups
This chapter assumes you can write a basic FIND ... RETURNING query, that you know the difference between SOSL and SOQL, and that you can run anonymous Apex in the Developer Console. Here you will learn how the IN clause limits which fields a SOSL search looks at, which groups exist, and which mistakes cause empty or surprising results.
What a search group does
A SOSL query has a search term and a scope. The term is what you look for. The scope is the set of fields that Salesforce checks for that term. You set the scope with the optional IN clause, which comes right after the search expression:
FIND {Acme} IN NAME FIELDS RETURNING Account(Id, Name)The words after IN name a search group. A search group is a predefined set of field types. Salesforce applies the group to every object in the RETURNING clause. You do not list individual fields in the IN clause. The RETURNING clause controls which fields come back. The IN clause controls which fields are searched. These are separate decisions.
If you leave out the IN clause, Salesforce uses ALL FIELDS. That default is the most flexible, but it can also return records you did not expect.
The available groups
| Group | What it searches | Typical use |
|---|---|---|
| `ALL FIELDS` | Every searchable text, email, and phone field. This is the default. | Free-text search boxes |
| `NAME FIELDS` | Name fields, such as Account Name, or Contact first and last name | Type-ahead and lookup search |
| `EMAIL FIELDS` | Email address fields | Finding a person by email |
| `PHONE FIELDS` | Phone number fields | Matching a caller to a record |
| `SIDEBAR FIELDS` | The fields that sidebar search covers, which are mostly name fields and some other key fields | Mimicking the classic sidebar search |
Two details are easy to miss:
ALL FIELDScovers fields of text, email, and phone types. It does not mean every field on the object. Number, date, checkbox, and similar fields are never part of a SOSL text search.- Which fields count as a "name field" depends on the object. For most standard objects the name field is obvious. For an object such as Case, the
Subjectis not a name field, so aNAME FIELDSsearch will not look in it.
Seeing the difference
Suppose a Contact is named Dana Reyes, works at Acme, and has the email [email protected]. Compare these two queries in the Developer Console or anonymous Apex:
List<List<SObject>> byName = [
FIND 'acme' IN NAME FIELDS
RETURNING Contact(Id, Name, Email)
];
List<List<SObject>> byAll = [
FIND 'acme' IN ALL FIELDS
RETURNING Contact(Id, Name, Email)
];
System.debug('NAME FIELDS: ' + byName[0].size());
System.debug('ALL FIELDS: ' + byAll[0].size());The first query returns nothing for Dana. Her name does not contain "acme", and NAME FIELDS ignores her email address. The second query matches her, because ALL FIELDS includes the email field, and the search index splits the email into word-like parts.
The choice of group changes the result. A narrower group gives you fewer, more relevant matches. A wider group gives you more matches and more noise.
Choosing a group
Pick the narrowest group that fits the user's intent.
- A lookup box where the user types part of a record's name should use
NAME FIELDS. Matches in descriptions or notes would only confuse the user. - A "find by email" feature should use
EMAIL FIELDS. SearchingALL FIELDSfor an email address can also match records that merely mention that address in a text field. - A caller-identification screen should use
PHONE FIELDS. See the next section for how phone numbers are matched. - A general search box where the user does not know what they are looking for should use
ALL FIELDS. - A feature that should behave like the standard sidebar search should use
SIDEBAR FIELDS.
flowchart TDThe decision above is easier to follow as a diagram.
Searching phone numbers
Phone searches have their own rules. Salesforce ignores formatting characters when it matches phone fields, so a search for 5551234567 can match a stored value of (555) 123-4567. You do not need to strip punctuation from the stored data.
String digits = '5551234567';
List<List<SObject>> results = [
FIND :digits IN PHONE FIELDS
RETURNING Contact(Id, Name, Phone), Lead(Id, Name, Phone)
];
List<Contact> contacts = (List<Contact>) results[0];
List<Lead> leads = (List<Lead>) results[1];
System.debug(contacts.size() + ' contacts, ' + leads.size() + ' leads');Leading wildcards behave differently for phone fields, and the details depend on the format of the stored data. If a phone search returns less than you expect, test it in the Developer Console with the digits alone before you add wildcards.
Groups apply to every object in RETURNING
The group is a property of the whole query. It is not set per object. If you search two objects with IN NAME FIELDS, Salesforce searches the name fields of both:
List<List<SObject>> results = [
FIND 'Global*' IN NAME FIELDS
RETURNING
Account(Id, Name),
Contact(Id, Name),
Opportunity(Id, Name)
];This query finds an Account named "Global Media", a Contact named "Globalina Cruz", and an Opportunity named "Global Rollout". It does not find an Opportunity with "Global" only in its description.
If one object needs a different scope from the others, run two separate queries. This is a common pattern when a screen searches people by name and also searches a custom object by a code stored in a text field. Each query costs one SOSL statement against the governor limit, so keep the number of separate queries small.
Groups in the other query forms
The IN clause is the same in every way you can run SOSL.
In static Apex, you write it inside square brackets, as in the examples above. In dynamic Apex with Search.query, you include it in the string:
public with sharing class ScopedSearch {
public static List<Contact> byEmail(String address) {
String safe = String.escapeSingleQuotes(address);
String query = 'FIND \'' + safe + '\' IN EMAIL FIELDS '
+ 'RETURNING Contact(Id, Name, Email LIMIT 10)';
List<List<SObject>> results = Search.query(query);
return (List<Contact>) results[0];
}
}In the REST API and in the Developer Console query editor, the search expression goes in braces and the IN clause follows it:
FIND {[email protected]} IN EMAIL FIELDS
RETURNING Contact(Id, Name, Email)Common errors
- Using a group name that does not exist.
IN TEXT FIELDSorIN ID FIELDSfails at compile time in static SOSL and at run time inSearch.query. Use only the five groups above. - Expecting
NAME FIELDSto search every text field called "name". Only the object's designated name fields count. Check the object's field definitions if a custom object does not behave as expected. - Putting the
INclause afterRETURNING. The order is fixed:FIND, thenIN, thenRETURNING. Reversing it is a syntax error. - Narrowing the group and forgetting the consequence. A user searching for "[email protected]" in a
NAME FIELDSquery will see no results, and the code will look broken when it is not. - Relying on a record that was just inserted. Records become searchable only after the search index updates. Salesforce does not guarantee this happens immediately, so a query that runs right after an
insertmay not find the new record. The testing chapter covers the supported workaround.
Summary of decisions
- Start from what the user knows: a name, an email, a phone number, or just some words.
- Choose the narrowest group that covers it.
- Remember that one group applies to all objects in the query.
- Use
ALL FIELDSonly when the user's intent is open-ended, and expect more results.
Exercise
A support agent types a customer's email address into a search box. The code currently runs FIND :term IN NAME FIELDS RETURNING Contact(Id, Name, Email) and always returns no records. Why, and how would you fix it?
Show answer
NAME FIELDS only searches name fields, and an email address does not appear in a contact's name. Change the scope to IN EMAIL FIELDS. If the box must accept names as well as emails, use IN ALL FIELDS instead, and accept that results may include records that mention the term in other text fields.
Exercise
You need one query that finds Accounts and Opportunities whose names start with "Orion", and also finds Opportunities whose description mentions "Orion". Can one SOSL query do this? Explain.
Show answer
No. The search group applies to every object in the RETURNING clause. A single query cannot use NAME FIELDS for the names and ALL FIELDS for the description match on only one object. Run two queries: one with IN NAME FIELDS for Accounts and Opportunities, and one with IN ALL FIELDS for Opportunities. Merge the results in Apex if needed, and count both against the SOSL query limit.