Sub topic 3
Writing a FIND clause
This chapter assumes you can write basic SOQL, read Apex variables, collections, and loops, and run anonymous Apex in the Developer Console. It builds on the overview of what SOSL is and when to choose it over SOQL. Here you learn how the FIND clause is written, how its search expression is parsed, and what causes the usual errors.
What the FIND clause does
Every SOSL query starts with FIND. The clause holds the search expression, which is the text Salesforce looks for in its search index. Salesforce does not scan the database tables for it. Everything after FIND (the scope and RETURNING) decides where to look and what to return.
A minimal query has two parts:
List<List<SObject>> results = [
FIND 'Acme'
RETURNING Account(Id, Name)
];
System.debug(results[0].size() + ' accounts matched');The search expression is 'Acme'. Because the query has no IN clause, it searches all searchable text fields. The search is case-insensitive, so acme, ACME, and Acme find the same records.
Two ways to write the expression
The search expression can be delimited in two ways. Which one you use depends on where the query runs.
| Where the query runs | Delimiter | Example |
|---|---|---|
| Static SOSL in Apex | Single quotes | `FIND 'Acme*'` |
| Static SOSL with a variable | Bind variable, no quotes | `FIND :term` |
| Developer Console query editor, REST API, `Search.query` | Curly braces | `FIND {Acme*}` |
Search.query accepts a string that uses either form. In the braces form, a phrase is written with double quotes inside the braces. In the Apex single-quoted form, the double quotes sit inside the string literal:
List<List<SObject>> results = [
FIND '"Acme Corp"'
IN NAME FIELDS
RETURNING Account(Id, Name)
];Search terms
A search expression is made of one or more terms. A term is a single word, a phrase, or a word with wildcards.
- A single word matches records that contain that word in a searched field.
FIND 'Acme'matches "Acme Corp" and "The Acme Group". - A phrase in double quotes matches those words together, in that order.
FIND '"Acme Corp"'does not match "Corp of Acme". - Matching is by whole word unless you add a wildcard.
FIND 'Acme'does not match a field that contains only "Acmeville".
Salesforce matches terms against its index, and the index works on words. That is why a search for a fragment from the middle of a word returns nothing even when LIKE '%fragment%' in SOQL would have matched. If you need substring matching on a single field, that is a reason to prefer SOQL.
Wildcards
Two wildcard characters are available:
*matches zero or more characters.?matches exactly one character.
Salesforce documents wildcards in the middle or at the end of a term. The following query matches "Acme", "Acmeville", and "Acme Industries":
List<List<SObject>> results = [
FIND 'Acme*'
IN NAME FIELDS
RETURNING Account(Id, Name)
];FIND 'Sm?th' matches "Smith" and "Smyth" but not "Smoothe". Very short terms with a wildcard can match a huge number of records. Use enough leading characters to keep the match set small.
Logical operators
You can combine terms with AND, OR, and AND NOT. Operators are written in uppercase. Parentheses group terms.
FIND {"Acme Corp" OR Globex* AND NOT Test}
IN NAME FIELDS
RETURNING Account(Id, Name), Opportunity(Id, Name)This is the braces form, so run it in the Developer Console query editor or send it to the REST search endpoint. Read it as: the exact phrase "Acme Corp", or a word starting with "Globex" that is not paired with "Test".
If you list several terms with no operator between them, Salesforce treats the space as OR. That surprises people who expect a space to mean "both words". Write the operator you mean.
// Records containing both words
List<List<SObject>> both = [
FIND 'Acme AND Berlin'
RETURNING Account(Id, Name)
];
// Records containing either word
List<List<SObject>> either = [
FIND 'Acme OR Berlin'
RETURNING Account(Id, Name)
];Operators have a precedence order, so a query that mixes AND and OR can read differently from how you intended it. Parentheses remove the doubt:
List<List<SObject>> results = [
FIND '(Acme OR Globex) AND NOT Test'
IN NAME FIELDS
RETURNING Account(Id, Name)
];How the search scope interacts with FIND
The IN clause comes right after the expression and chooses which fields the terms are matched against. The options are ALL FIELDS, NAME FIELDS, EMAIL FIELDS, PHONE FIELDS, and SIDEBAR FIELDS. If you leave IN out, the search uses ALL FIELDS.
The scope changes which records match, not the shape of the result. The next chapter covers the groups in detail. For now, remember that FIND 'Acme' IN NAME FIELDS matches fewer records than FIND 'Acme' because it ignores text in other fields, such as a description.
Reserved characters and escaping
Some characters have a meaning inside a search expression. To search for them literally, put a backslash in front of each one. The reserved characters are:
& | ! ( ) { } [ ] ^ " ' ~ * ? : \ + -
A search for the literal text AT&T needs the ampersand escaped. In an Apex string literal the backslash itself must be doubled, because Apex also treats a backslash as an escape character:
List<List<SObject>> results = [
FIND 'AT\\&T'
IN NAME FIELDS
RETURNING Account(Id, Name)
];Apex turns \\ into a single backslash, and SOSL then sees \&. Forgetting the double backslash is a common cause of a compile error or of a search that quietly matches the wrong thing.
Quoting and escaping become a security matter when the term comes from a user. A later chapter covers String.escapeSingleQuotes and dynamic SOSL. The rule to keep for now is that a user-supplied value should go in through a bind variable whenever the query is static.
Bind variables in the FIND clause
A bind variable lets the search term come from Apex code. Write a colon before the variable name and leave off the quotes:
String term = 'Acme*';
List<List<SObject>> results = [
FIND :term
IN NAME FIELDS
RETURNING Account(Id, Name)
];The variable's value is the whole search expression. If it contains a wildcard, an operator, or a phrase in double quotes, the search engine interprets it. Salesforce does not treat the bound value as a plain literal word. A user who types Acme OR Globex therefore searches for both. For many search boxes that is what you want. When it is not, strip or escape the special characters before you bind the value.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `MALFORMED_SEARCH` or no search term found | The term is empty, too short, or only wildcards | Check the value before you run the query |
| Compile error on a quote | A single quote or backslash inside a static string | Use a bind variable, or escape the character |
| A word from the middle of a field text is not found | The index matches whole words | Add a wildcard, or use SOQL `LIKE` on one field |
| Multi-word input returns far too many rows | A space is treated as `OR` | Use `AND`, or wrap the words in double quotes |
| A record you just created is not found | The search index updates after a short delay | Wait, or in tests use fixed search results |
Putting it together
This example builds a search from a user-typed value. It rejects short input before any query runs, then groups terms with parentheses and uses a bind variable:
public with sharing class QuickSearch {
public static List<Account> byName(String userInput) {
if (String.isBlank(userInput) || userInput.trim().length() < 2) {
return new List<Account>();
}
String term = '(' + userInput.trim() + '*) AND NOT Test';
List<List<SObject>> results = [
FIND :term
IN NAME FIELDS
RETURNING Account(Id, Name LIMIT 20)
];
return (List<Account>) results[0];
}
}Note that userInput can still contain reserved characters. Production code should escape them first, as the chapter on dynamic SOSL shows.
Exercise
A developer writes FIND 'Acme Berlin' RETURNING Account(Id, Name) and expects only accounts that mention both words. The query returns many accounts that mention only one. What is the cause, and how would you rewrite the query so that only records containing both words match?
Show answer
A space between terms is treated as OR, so a record that contains either word matches. Write the operator explicitly: FIND 'Acme AND Berlin' RETURNING Account(Id, Name). To match the two words as an exact phrase, in that order, use FIND '"Acme Berlin"' RETURNING Account(Id, Name).
Exercise
You need a static query that finds contacts whose name fields contain a literal ampersand in the term R&D. How must the term be written in an Apex string literal?
Show answer
Escape the ampersand with a backslash for SOSL, and double that backslash for Apex: FIND 'R\\&D' IN NAME FIELDS RETURNING Contact(Id, Name). Apex reads \\ as one backslash, so SOSL receives R\&D.