Sub topic 9
Passing values with bind variables
This chapter assumes you can write a basic static SOSL query in Apex and read the List<List<SObject>> result. It also assumes you know how bind variables work in SOQL, using a colon before a variable name. SOSL uses the same syntax in a few more places. You will see where binds are allowed, what they protect you from, and what they don't.
What a bind variable does in SOSL
A bind variable is an Apex variable or expression that you reference inside a static query by putting a colon in front of it. The Apex compiler checks the query when the class is saved. At run time, Apex passes the variable's current value to the search engine as data. It never pastes the value into the query text.
Without binds, you would build a string and call Search.query. With binds, you write the query inline and the compiler checks the objects, fields, and clauses for you.
public with sharing class AccountSearchService {
public static List<Account> searchByName(String term) {
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name)
];
return (List<Account>) results[0];
}
}The value of term becomes the search text. If a caller passes O'Brien, the apostrophe cannot end the query early, because the value was never part of the query text.
Where bind variables are allowed
You can use a bind variable in three places in a static SOSL query:
| Location | Example | Notes |
|---|---|---|
| The search term in `FIND` | `FIND :term` | The variable must be a `String`. |
| `WHERE` inside a RETURNING object | `Account(Id WHERE Industry = :industry)` | Works like SOQL binds, including `IN :collection`. |
| `LIMIT` inside a RETURNING object | `Account(Id LIMIT :maxRows)` | The variable must be an `Integer`. |
You cannot bind object names, field names, or search groups. The following does not compile, because IN :scope would need to change the structure of the query:
String scope = 'NAME FIELDS';
// Does not compile: structure cannot be bound.
// List<List<SObject>> r = [FIND 'Acme' IN :scope RETURNING Account(Id)];If you need a different scope or object list at run time, you have to build the query as a string. That approach is covered in the chapter on dynamic SOSL.
A complete example with several binds
The next class uses all three kinds of bind in one query. It takes a search term, a list of industries, and a row limit.
public with sharing class TechAccountSearch {
public static List<Account> find(String term, List<String> industries, Integer maxRows) {
List<List<SObject>> results = [
FIND :term IN ALL FIELDS
RETURNING
Account(
Id, Name, Industry
WHERE Industry IN :industries
ORDER BY Name
LIMIT :maxRows
)
];
return (List<Account>) results[0];
}
}You could call it from anonymous Apex like this:
List<Account> hits = TechAccountSearch.find(
'Acme*',
new List<String>{ 'Technology', 'Energy' },
10
);
for (Account a : hits) {
System.debug(a.Name + ' (' + a.Industry + ')');
}The IN :industries filter is applied to the records the search matched. The search engine finds matching text first, and the WHERE clause then narrows that set.
Adding wildcards and operators to a bound value
A bound value is still search text. The search engine interprets the characters * and ? as wildcards, and it interprets ", AND, OR, and AND NOT as operators. So you can build the pattern in Apex and bind the result:
public with sharing class PrefixSearch {
public static List<Contact> byLastNamePrefix(String prefix) {
String pattern = prefix + '*';
List<List<SObject>> results = [
FIND :pattern IN NAME FIELDS
RETURNING Contact(Id, FirstName, LastName ORDER BY LastName LIMIT 25)
];
return (List<Contact>) results[0];
}
}This is useful, but it has one consequence. A bind variable prevents the value from changing the structure of the query. It does not stop the value from changing the meaning of the search. If a user types Acme OR Globex into a search box and you bind it directly, the engine treats OR as an operator. If a user types *, the engine gets a bare wildcard. Decide whether that is acceptable for your feature.
Guarding the search term
Static SOSL fails at run time if the search term is unusable. Two cases come up often.
- Null or empty term. A null or blank
FINDvalue raises aQueryException. - Term too short. The search engine requires at least two characters, not counting wildcards. A single letter, or a term like
a*, can raise aQueryException.
Check the value before you run the query, and return an empty result instead of letting the exception reach the user:
public with sharing class SafeSearch {
private static final Integer MIN_LENGTH = 2;
public static List<Account> search(String rawTerm) {
if (String.isBlank(rawTerm)) {
return new List<Account>();
}
String term = rawTerm.trim();
if (term.replace('*', '').replace('?', '').length() < MIN_LENGTH) {
return new List<Account>();
}
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name LIMIT 20)
];
return (List<Account>) results[0];
}
}The length check removes the wildcard characters before it counts, so a* is rejected, and ac* is accepted.
Binding expressions and object fields
You can bind more than a plain local variable. A bind can reference a field of an object variable, such as :request.SearchText__c. It can also reference a member of a wrapper class. Keep binds simple. If you need to combine values, compute the result into a local variable first, and bind that variable. This keeps the query readable and makes the value easy to log while you debug.
public with sharing class RequestSearch {
public class SearchRequest {
public String text;
public Integer maxRows;
}
public static List<Account> run(SearchRequest request) {
String term = request.text;
Integer cap = request.maxRows == null ? 20 : request.maxRows;
List<List<SObject>> results = [
FIND :term IN NAME FIELDS
RETURNING Account(Id, Name LIMIT :cap)
];
return (List<Account>) results[0];
}
}The ternary expression supplies a default before the query runs. This is clearer than putting the logic inside the query.
Common errors
- Binding a non-String in FIND. The search term must be a
String. Convert other types first, for example withString.valueOf(n). - Binding a field or object name. The compiler rejects this. Use dynamic SOSL instead.
- Expecting wildcards to be added for you.
FIND :termsearches for exactly what is interm. Add*yourself if you want prefix matching. - Forgetting that variables must be in scope. A bind variable has to be declared in the same method or be a member of the class. A name that is not visible gives a compile error, not a run-time error.
- Reusing a user-entered operator by accident. A user who types a leading
-or the wordNOTmay get an unexpected search. Escape or reject special characters if your users are not expected to know the syntax. - Binding a null
LIMIT. A nullIntegerinLIMIT :capfails at run time. Default the value, as in theRequestSearchexample.
When to use binds and when to use a string
Prefer a static query with binds whenever the structure is fixed and only the values change. You get compile-time checking, a dependency record on the fields you reference, and no injection risk to the query structure. Move to Search.query only when the objects, fields, or scope must change at run time. In that case you take on the work of escaping values yourself.
Exercise
A method receives a user-entered String named input and runs [FIND :input IN NAME FIELDS RETURNING Account(Id, Name)]. The user types Acme" OR Name != null. Can this change which objects or clauses the query uses? Can it change what the search matches?
Show answer
It cannot change the structure of the query, such as the objects, fields, or clauses, because the value is bound as data and is not pasted into the query text. It can still change what the search matches, because the engine reads the bound value as search text and treats characters such as quotes and operators like OR according to search syntax. To search for those characters literally, escape them in the value before binding, or reject input that contains them.
Exercise
Which parts of this static SOSL cannot be replaced by a bind variable: the search term, the object name in RETURNING, the field list in an object, the LIMIT value, the value in a WHERE comparison?
Show answer
The object name in RETURNING and the field list cannot be bound. The search term (String), the LIMIT value (Integer), and the value in a WHERE comparison can all be bound. If the object or field names must vary at run time, build the query as a string and use Search.query.
Exercise
Write a static SOSL query that searches Account name fields for a String variable prefix followed by a wildcard, and returns at most maxRows records.
Show answer
String pattern = prefix + '*';
List<List<SObject>> results = [
FIND :pattern IN NAME FIELDS
RETURNING Account(Id, Name LIMIT :maxRows)
];
The wildcard is added in Apex before binding, because FIND :prefix would search for the exact text without a wildcard. maxRows must be a non-null Integer.