Sub topic 5
Wildcards, Phrases, and AND, OR, AND NOT
This chapter covers how to write the search expression inside a FIND clause. It assumes you can already write a basic FIND ... RETURNING query, know the search groups (IN NAME FIELDS and so on), and can run anonymous Apex. Here you will learn how SOSL matches partial words, exact phrases, and combinations of terms.
How SOSL reads a search expression
SOSL searches a text index, not the raw field values. The index splits text into words (tokens) at spaces and most punctuation, and matching ignores case. A search for acme finds Acme, ACME, and Acme Corp, because each contains the whole word.
Whole-word matching is the main difference from SOQL's LIKE. FIND {cme} does not find Acme, because cme is not a word in the index. To match part of a word, you add a wildcard.
The expression sits in one of two forms:
- Braces:
FIND {Acme Corp}. This is what the REST search endpoint and the Developer Console query editor use. - Single quotes in Apex:
FIND 'Acme*'. This is what static and dynamic SOSL in Apex use.
The expression syntax is the same in both forms. Only the delimiters and the escaping rules differ.
Wildcards
SOSL has two wildcard characters.
| Wildcard | Matches | Example | Finds |
|---|---|---|---|
| `*` | Zero or more characters | `Acm*` | Acme, Acmeco, Acm |
| `?` | Exactly one character | `Sm?th` | Smith, Smyth |
Both wildcards work at the end or in the middle of a term. Do not rely on a wildcard at the start of a term, such as *corp. Leading wildcards are generally unsupported, so start from the beginning of the word you know.
List<List<SObject>> results = [
FIND 'Glob*' IN NAME FIELDS
RETURNING Account(Id, Name)
];
List<Account> accounts = (List<Account>) results[0];
System.debug(accounts.size() + ' accounts start with Glob');Some details matter in practice:
- Give the search at least two real characters before the wildcard. A single character such as
a*is rarely accepted, and it would match too much to be useful anyway. - A wildcard term is a prefix match on a word.
Acme*findsAcme CorpandAcmeville, but notBig Acme... unlessAcmeis its own word in that value. InBig Acme, it is, so the record does match. The index matches any word, not only the first. - Terms without wildcards can also match word variants in some languages. For example,
runmay matchrunning. A term with a wildcard skips this behavior, which can makerun*andrunreturn different sets. - Do not put wildcards inside a quoted phrase and expect them to expand. Test it before depending on it.
Phrases
To require several words together and in order, wrap them in double quotes.
FIND {"Acme Corp"} IN NAME FIELDS RETURNING Account(Id, Name)Without the quotes, Acme Corp is two separate terms, and a record can match on either word depending on the operator between them. With the quotes, only values containing Acme immediately followed by Corp match.
In Apex, the expression is already inside single quotes, so the phrase quotes go inside them:
List<List<SObject>> results = [
FIND '"Acme Corp"' IN NAME FIELDS
RETURNING Account(Id, Name)
];Quotes also turn off operator handling. Inside a phrase, AND and OR are ordinary words. This is useful when the text you search for contains an operator word, such as a company named Black AND Decker.
Logical operators
You can combine terms with three operators.
| Operator | Meaning | Example |
|---|---|---|
| `AND` | Both terms must match | `Acme AND Widget` |
| `OR` | Either term can match | `Acme OR Globex` |
| `AND NOT` | The first term matches and the second does not | `Acme AND NOT Test` |
AND NOT is a single operator written as two words. You use it between two terms, so a query cannot begin with NOT.
Write operators in uppercase. Lowercase and may be read as a search word instead, so uppercase keeps the intent clear. Also write the operator explicitly between terms and do not rely on a space to mean AND or OR. An explicit operator makes the query readable and keeps the behavior from depending on how the default works.
Precedence and parentheses
When one expression mixes operators, SOSL evaluates parentheses first, then NOT, then AND, then OR. This surprises people who read left to right:
FIND {Acme OR Globex AND Test} IN NAME FIELDS RETURNING Account(Id, Name)Because AND binds tighter than OR, this means Acme OR (Globex AND Test). A record named only Acme matches. If you meant "either company, and also Test", add parentheses:
FIND {(Acme OR Globex) AND Test} IN NAME FIELDS RETURNING Account(Id, Name)Parentheses cost nothing and remove doubt. Use them whenever an expression has more than one kind of operator.
Combining all three
This query from the braces form uses a phrase, a wildcard, and two operators together:
FIND {"Acme Corp" OR Globex* AND NOT Test}
IN NAME FIELDS
RETURNING Account(Id, Name), Opportunity(Id, Name)By the precedence rules, NOT and AND combine first, so this reads as "Acme Corp" OR (Globex* AND NOT Test). An account named Acme Corp Test still matches through the first branch, because the exclusion applies only to the Globex* branch. If you want to exclude Test everywhere, group the OR:
FIND {("Acme Corp" OR Globex*) AND NOT Test}
IN NAME FIELDS
RETURNING Account(Id, Name), Opportunity(Id, Name)Special characters and escaping
Some characters have meaning inside a search expression: ? & | ! { } [ ] ( ) ^ ~ * : \ " ' + -. To search for one literally, put a backslash before it. To find Smith (Acme) literally in the braces form, write Smith \(Acme\).
In Apex, a backslash inside a string must itself be doubled when you write it in a string literal, so check what the string contains at run time, not only what it looks like in source.
This matters most when the search term comes from a user. A user who types * or Acme OR can change the meaning of your query, and an unescaped quote can break it. The String.escapeSingleQuotes method only handles single quotes, so it does not stop users from injecting operators or wildcards. A helper that escapes every special character and wraps the input as a phrase gives users a plain "find this text" search:
public with sharing class SafeSearch {
public static String escape(String raw) {
return raw.replaceAll('([\\\\?&|!{}\\[\\]()^~*:"\\'+\\-])', '\\\\$1');
}
public static List<Account> findByPhrase(String userInput) {
String query = 'FIND {"' + escape(userInput) + '"} '
+ 'IN NAME FIELDS RETURNING Account(Id, Name LIMIT 20)';
List<List<SObject>> results = Search.query(query);
return (List<Account>) results[0];
}
}Run SafeSearch.findByPhrase('Acme*') in anonymous Apex. The * is escaped and treated as plain text, so it no longer acts as a wildcard. If you want users to have wildcards, escape everything except * and validate that the term has enough real characters.
Common mistakes
- Searching for part of a word without a wildcard.
FIND {cme}finds nothing, andFIND {Acm*}works. - Expecting a leading wildcard to work. Rewrite the search to start from a known word beginning.
- Mixing
ORandANDwithout parentheses and getting records you did not expect. - Leaving a phrase unquoted.
Acme Corpbecomes two terms. - Passing unescaped user input into
Search.query. - Starting with
NOT. UseAND NOTbetween two terms.
Exercise
A query reads FIND {Acme OR Globex AND NOT Test}. A record is named "Acme Test". Is it returned? Rewrite the expression so that any record containing Test is excluded.
Show answer
Yes, it is returned. AND NOT binds tighter than OR, so the expression means Acme OR (Globex AND NOT Test). "Acme Test" matches the Acme branch, so the exclusion never applies to it. To exclude Test everywhere, group the OR: FIND {(Acme OR Globex) AND NOT Test}.
Exercise
You build a dynamic search from user text. A user types: Acme* OR Globex. Using the SafeSearch.findByPhrase helper from this chapter, how does SOSL treat that input, and why?
Show answer
As one literal phrase. The helper puts a backslash before the and wraps the whole input in double quotes. The is plain text, not a wildcard. OR is an ordinary word inside the phrase, not an operator.