Sub topic 13
Optional refinements: highlighting, snippets, and WITH clauses
This chapter covers the optional clauses that come after RETURNING in a SOSL query. It assumes you can already write a FIND query with a RETURNING clause and run it in Apex. You should also know how List<List<SObject>> results are laid out. None of these refinements are needed for a basic search. They are useful when you show results to users, work with Knowledge or Experience Cloud, or need to narrow a search by division, category, or price book.
Where the refinements go
A SOSL query has a fixed clause order. The WITH clauses sit after RETURNING, and the overall LIMIT comes last.
The IN clause and the WITH clauses are all optional. You can repeat WITH, as in WITH DIVISION = 'Global' WITH SPELL_CORRECTION = true, but each kind of WITH clause can appear only once.
FIND {warranty}
IN ALL FIELDS
RETURNING Case(Id, Subject, Description)
WITH DIVISION = 'Global'
WITH SNIPPET (target_length=120)
LIMIT 20Some WITH clauses depend on features your org must have turned on, such as divisions, Salesforce Knowledge, or Experience Cloud. If the feature is off, the query fails when it runs.
Overview of the WITH clauses
| Clause | What it does | Needs |
|---|---|---|
| `WITH HIGHLIGHT` | Wraps matched search terms in `<mark>` tags | Nothing extra |
| `WITH SNIPPET (target_length=n)` | Returns a short excerpt around the match | Supported objects such as Knowledge, Case, and Feed |
| `WITH DIVISION = 'name'` | Limits results to one division | Divisions enabled |
| `WITH DATA CATEGORY ...` | Filters Knowledge articles by category | Salesforce Knowledge |
| `WITH NETWORK = 'id'` | Limits results to one Experience Cloud site | Experience Cloud |
| `WITH PricebookId = 'id'` | Limits product results to one price book | Products and price books |
| `WITH METADATA = 'LABELS'` | Returns field labels along with the data | API access |
| `WITH SPELL_CORRECTION = true` | Corrects misspelled search terms | API support for the search |
Support can differ between Apex, REST, and SOAP, and it can change between API versions. Check the SOSL reference for your API version before depending on a clause in production code.
Highlighting matched terms
WITH HIGHLIGHT asks the search to mark where your terms matched. In the returned field values, matched text is wrapped in <mark> and </mark> tags. For example, searching for acme can return the name <mark>Acme</mark> Corp.
FIND {acme}
IN NAME FIELDS
RETURNING Account(Id, Name)
WITH HIGHLIGHTYou can then render the value in a UI that understands the tags, such as a Lightning Web Component using lightning-formatted-rich-text. The tags are part of the string, so you must account for them in any code that compares or stores the value.
Snippets
A snippet is a short excerpt of a long text field, centred on the match. Use it when showing the whole Description or article body would crowd the results page.
WITH SNIPPET takes an optional target_length, the approximate number of characters in the excerpt. The default is 120. Snippets work only on certain objects, including Knowledge articles, cases, case comments, feed items, feed comments, and ideas. On other objects the clause has no useful effect.
Static SOSL and Search.query return plain SObject lists, so they have no place to put a snippet. To read snippets in Apex, use Search.find. It returns a Search.SearchResults object that wraps each record in a Search.SearchResult.
Search.SearchResults found = Search.find(
'FIND {warranty} IN ALL FIELDS ' +
'RETURNING Case(Id, Subject, Description) ' +
'WITH SNIPPET (target_length=120)'
);
List<Search.SearchResult> caseResults = found.get('Case');
for (Search.SearchResult result : caseResults) {
Case c = (Case) result.getSObject();
System.debug(c.Subject + ' -> ' + result.getSnippet());
}Three details to note:
- You look up each object's results by its API name, here
'Case', not by a list position as withresults[0]. getSObject()returns a genericSObject, so you cast it to the type you expect.getSnippet()returns the excerpt of the field text that matched. If the record matched only on a field that has no snippet, the value can be null, so check before you use it.
Narrowing by division
Divisions split a large org's data into logical groups, for example by region. With divisions enabled, WITH DIVISION limits the search to one of them.
FIND {Globex*}
IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, Name)
WITH DIVISION = 'Global'The division is given by name. The special value 'Global' refers to records that belong to the global division. Without this clause, SOSL searches across the divisions that apply to the current user's settings.
Filtering Knowledge articles by data category
Salesforce Knowledge organises articles into data category groups, such as Geography with categories Europe and Asia. WITH DATA CATEGORY limits an article search to a category.
FIND {return policy}
IN ALL FIELDS
RETURNING KnowledgeArticleVersion(Id, Title
WHERE PublishStatus = 'Online' AND Language = 'en_US')
WITH DATA CATEGORY Geography__c ABOVE_OR_BELOW Europe__cThe category filter uses a group name, a position keyword, and a category name. The keywords are AT, ABOVE, BELOW, and ABOVE_OR_BELOW. ABOVE_OR_BELOW includes the category you name, its parents, and its children. Combine several conditions with AND.
Searching KnowledgeArticleVersion requires a PublishStatus filter in the per-object WHERE clause. Without it the query fails.
Experience Cloud sites and price books
WITH NETWORK limits results to records visible in a given Experience Cloud site. You give it the site's ID, or a list of IDs.
FIND {onboarding}
IN ALL FIELDS
RETURNING FeedItem(Id, Body)
WITH NETWORK = '0DBxx0000000001'WITH PricebookId narrows product results to the entries of one price book, and it is meant for searches that return Product2 or PricebookEntry records.
FIND {cable}
IN NAME FIELDS
RETURNING Product2(Id, Name)
WITH PricebookId = '01sxx0000000001'The IDs above are placeholders. In Apex, look up the real ID with a query or a custom setting. Do not hard-code it, because IDs differ between sandboxes and production.
Metadata and spelling
WITH METADATA = 'LABELS' adds field labels to the response, which helps a client that has to display column headings without a separate describe call. It is aimed at the REST and SOAP APIs.
WITH SPELL_CORRECTION = true lets the search correct a misspelled term, so Acmee can still find Acme. If the search corrects your term, the response says so. Because the search may use a different term from the one you typed, show the user what was actually searched.
Combining refinements and the failure modes
You can combine clauses. A typical self-service search might use WITH NETWORK, WITH SNIPPET, and WITH SPELL_CORRECTION. Keep these points in mind:
- Order of clauses. WITH clauses go after RETURNING and before the final LIMIT. A misplaced clause gives a parse error.
- Feature not enabled.
WITH DIVISIONin an org without divisions, orWITH DATA CATEGORYwithout Knowledge, fails at run time. - Unsupported object. A snippet request on an object that does not support snippets gives no excerpt.
- Security. These clauses change what is searched, not who may see it. Sharing rules and field access still apply as described in the earlier chapter on limits and security.
- Testing.
Test.setFixedSearchResultsreturns the IDs you list, so a test can confirm that your code handlesSearch.findresults. It cannot confirm that a snippet or a highlight is correct. Verify those against real data in a sandbox.
Exercise
A support portal search returns Case records with long Description fields. You want to show a short excerpt around the matched words for each case, in Apex. Which clause do you add, and which Apex method do you use to run the query and read the excerpt?
Show answer
Add WITH SNIPPET (target_length=n) after the RETURNING clause, and run the query with Search.find. Read the excerpt with getSnippet() on each Search.SearchResult, and get the record with getSObject(). Static SOSL and Search.query return plain SObject lists, so they cannot expose the snippet.
Exercise
This query fails with a parse error. What is wrong, and how do you fix it? FIND {Acme} RETURNING Account(Id, Name) LIMIT 10 WITH DIVISION = 'Global'
Show answer
The WITH clause is after LIMIT. WITH clauses must come after RETURNING and before the overall LIMIT. The fixed query is: FIND {Acme} RETURNING Account(Id, Name) WITH DIVISION = 'Global' LIMIT 10