SOSL in Apex

SOSL in Apex works much like SOQL in Apex. Queries are enclosed in square brackets and compiled directly into the code, ensuring that the query syntax is correct and references valid fields and objects in the database.

As with SOQL, bind variables can be used to inject variable values from the running program into select parts of the query. This injection of values is performed in a secure manner because Apex automatically escapes special characters. Bind variables are allowed in the search string (following FIND), filter literals (in the WHERE block), and the LIMIT keyword.

SOSL is not allowed in triggers. It will compile, but will fail at runtime. It is allowed in unit tests and custom user interfaces, as covered in Chapter 6, “User Interfaces.” In this chapter, you can experiment with SOSL using the Execute Anonymous view.


Note

You are limited to 20 SOSL queries returning a maximum of 2,000 rows per query.


Listing 5.17 is a sample SOSL query in Apex. It returns the names of records in the Project and Contact objects that contain the word Chicago in any of their fields.

Listing 5.17 SOSL in Apex


List<List<SObject>> result = [
  FIND 'Chicago'
  RETURNING Project__c(Name), Contact(Name)
];
List<Project__c> projects = (List<Project__c>)result[0];
for (Project__c project : projects) {
  System.debug('Project: ' + project.Name);
}
List<Contact> resources = (List<Contact>)result[1];
for (Contact resource : resources) {
  System.debug('Contact: ' + resource.Name);
}


Figure 5.5 shows the results of running this code in the Execute Anonymous view. If your debug log is cluttered with too many other entries to see the output of the query, set Apex code to the Debug level and all other Log categories to None.

Image

Figure 5.5 Results of SOSL in Apex

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.226.24