Exploring Salesforce Object Search Language (SOSL): SOSL Syntax Overview
SOSL (Salesforce Object Search Language) provides a comprehensive text-based search capability across multiple Salesforce objects. In the introduction to Salesforce Object Search Language (SOSL), we explored its role as a powerful tool for performing efficient text-based searches across multiple Salesforce objects and fields, highlighting its advantages over SOQL for broad, flexible searches when the exact data location is unknown. This will focus on the syntax structure and components of SOSL queries.
Find Clause (Required)
Section titled “Find Clause (Required)”The FIND {SearchQuery} clause is the only required component of a SOSL query, specifying the text to search for. The syntax differs slightly between Apex and the API: in Apex, the search term is enclosed in single quotes, while in the API, it is enclosed in curly brackets:
FIND {SearchQuery}FIND 'SearchQuery'How SOSL Single Word Matching Actually Works
Section titled “How SOSL Single Word Matching Actually Works”Word Tokenization and Search Index: SOSL uses a search index that tokenizes text fields, breaking down content into individual searchable terms. When you search for a single word like FIND {John}, SOSL will match:
- Records where
Johnappears as a complete word. - Records where
Johnappears as part of larger words (like “Johnson” or “Johnny”). - Records where “John” appears in compound words or phrases.
Search Query Components
Section titled “Search Query Components”- Single words: You can search for individual words using the FIND clause. For example,
FIND {test}orFIND {hello}will search for these specific words across the specified fields. - Phrases: To search for exact phrases, enclose them in double quotes. For instance,
FIND {"john smith"}(enclosed in double quotes) will look for the exact phrase “john smith” in the data. - Wildcards: Use wildcards to broaden your search. The asterisk
*matches zero or more characters e.g.FIND {prospect*}would find “prospect”, “prospects”, “prospecting” etc. The question mark?matches exactly one character, soFIND {jo?n}would find “john” or “joan” - Logical Operators: Enhance your search with logical operators like
AND,OR,AND NOTQuotations""and Parentheses(). These allow you to create complex search conditions, such asFIND {Technology AND (Software OR Cloud)}to find records containing “Technology” and either “Software” or “Cloud.” Use quotation marks around search terms to find matches in the order you entered your search terms.
Search Behavior Characteristics
Section titled “Search Behavior Characteristics”- Text-Based Fuzzy Matching: The search engine analyzes text fields and can return partial matches based on relevance.
- Tokenization Process: SOSL tokenizes content during indexing, creating searchable terms from larger text strings.
- Case-Insensitive: Searching for
Customer,customer, orCUSTOMERreturns identical results.
IN SearchGroup (Optional)
Section titled “IN SearchGroup (Optional)”In an SOSL query, the optional IN SearchGroup clause allows you to specify which types of text fields to search within the objects. This clause defines the scope of the search, helping to narrow it down and improve both performance and relevance of results. If the IN clause is omitted, SOSL will search across all text fields by default. You can choose from different search group options, such as name, email, phone, sidebar, or all fields, to tailor your search to specific needs.
Here are the different search group options and what they mean:
- ALL FIELDS: This option searches across all text fields in the specified objects. It is the broadest search scope and is useful when you are unsure of where the data might reside.
- NAME FIELDS: This option restricts the search to name fields, such as the
Namefield on the Account object or theFirstNameandLastNamefields on the Contact object. It is ideal for searches focused on identifying records by their names. - EMAIL FIELDS: This option limits the search to email fields, making it useful for finding records based on email addresses. It is particularly helpful in scenarios where you need to locate contacts or leads using their email information.
- PHONE FIELDS: This option confines the search to phone fields, allowing you to find records based on phone numbers. It is beneficial when searching for contacts or accounts using their phone contact details.
- SIDEBAR FIELDS: Search for valid records as listed in the Sidebar dropdown list. Unlike search in the application, the asterisk
*wildcard isn’t appended to the end of a search string. Sidebar fields refers to fields displayed in the Salesforce sidebar areas of record pages and user interface components.
By using the IN SearchGroup clause with specific search groups, you can tailor your SOSL queries to be more efficient and targeted, ensuring that you retrieve the most relevant results for your search criteria.
RETURNING FieldSpec (Optional)
Section titled “RETURNING FieldSpec (Optional)”The RETURNING FielsSpec clause in SOSL is an optional component that specifies which objects and fields should be returned in the search results. If omitted, the default behavior is to return only the IDs of all searchable objects that match your search criteria. The RETURNING clause gives you control over exactly what data is retrieved from your search.
The RETURNING clause itself has optional clauses include WHERE for filtering results, ORDER BY for sorting results, LIMIT for specifying the maximum number of records, and OFFSET for pagination.
The format is:
RETURNING ObjectTypeName[(FieldList [WHERE] [USING Listview=listview name] [ORDER BY Clause] [LIMIT n] [OFFSETn])] [, ObjectTypeName [(FieldList [WHERE] [ORDER BY Clause] [LIMITn] [OFFSETn])]]Key Components
Section titled “Key Components”- ObjectTypeName: Specifies the type of object to return in the search results, which can be either standard objects like Account, Contact, or Lead, or custom objects defined in your Salesforce environment. You can list multiple distinct objects separated by commas, allowing you to retrieve data from various sources in a single query. If included, the search will only return objects that are explicitly specified in the
RETURNINGclause, ensuring that the results are focused and relevant to your needs. - FieldList: An optional comma-separated list of fields to return for the specified object. If you include a FieldList, these fields are returned for all found objects. The format supports relationship fields with the same depth as SOQL.
- WHERE: Optional filtering clause to restrict the results based on field values for the given object. You must include a
FieldListwith at least one field to useWHERE. If unspecified, the search retrieves all the rows in the object that are visible to the user. For example:RETURNING Account (Name, Industry WHERE Name LIKE 'test') - ORDER BY: Optional clause to specify result ordering, including ascending/descending order and null handling. Requires a
FieldListwith at least one field. For example:RETURNING Account (Name, Industry ORDER BY Name Desc) - LIMIT n: Optional clause to set the maximum number of records returned for the specific object. Must include a
FieldListwith at least one field. For example:RETURNING CustomObject__c (Name, CustomField__c LIMIT 10) - OFFSET n: An optional clause for result pagination, specifying the starting row offset. It can only be used when querying a single object and must be the last clause specified. It requires a
FieldListwith at least one field. For example:RETURNING Account (Name, Industry OFFSET 100) - USING ListView: Optional clause used to search within a single given object’s list view. Only one list view can be specified. Only the first 2,000 records of the list view are searched, according to the sort order the user has set for the list view. ListView=Recent searches for the most recently accessed items viewed or referenced by the current user.
These components allow you to tailor the RETURNING clause to retrieve specific data efficiently, enhancing the flexibility and precision of your SOSL queries.
There are also a number data formatting functions including toLabel(field) to return translated field labels, convertCurrency(Amount) to converts to user’s currency (if multi-currency enabled) and FORMAT to apply localized formatting to standard and custom number, date, time, and currency fields.
WITH (Optional)
Section titled “WITH (Optional)”SOSL provides numerous advanced filtering options through various WITH clauses that allow you to refine search results, enhance presentation, and apply specific organizational constraints. Here’s a comprehensive overview of all available WITHfilter options:
Knowledge Management and Content Filtering
WITH DATA CATEGORY
Section titled “WITH DATA CATEGORY”This optional clause is used in searches of Salesforce Knowledge articles and questions and can be added to a SOSL query to filter all search results that are associated with one or more data categories and are visible to users. It uses operators like AT, ABOVE, BELOW, and ABOVE_OR_BELOW to match categories and their hierarchical relationships.
Syntax: WITH DATA CATEGORY DataCategorySpec [logicalOperator DataCategorySpec2 …]
Where DataCategorySpec consists of:
- groupName: The name of the data category group to filter.
- Operator: The operator to use, such as
ATto query the specified data category,ABOVE/BELOWto query the specified data category and all of its parent categories / subcategories. WhileABOVE_OR_BELOWqueries the specified data category, all of its parent categories, and all of its subcategories. - category: The name of the category to filter. Multiple categories can be included by enclosing them in parentheses, separated by commas.
You can add multiple data category specifiers using the logical operator AND. Other operators, such as OR and AND NOT, are not supported.
A SOSL statement using the WITH DATA CATEGORY clause must also include a RETURNING ObjectTypeName clause, with a WHERE clause that filters on the PublishStatus field.
Example
FIND {tourism} RETURNING KnowledgeArticleVersion (Id, Title WHERE PublishStatus='online') WITH DATA CATEGORY Location__c AT America__cSearch all published (online) Salesforce Knowledge articles with a category from one category group
WITH SNIPPET
Section titled “WITH SNIPPET”The WITH SNIPPET clause is an optional component in a SOSL query that generates contextual text excerpts with highlighted search terms for articles, cases, feeds, and ideas. This feature enhances the search results by providing users with snippets that make it easier to identify relevant content quickly.
Key Features:
- Highlighted Matches: On the search results page, snippets show terms matching the search query highlighted within the context of surrounding text. This helps users quickly identify the content they’re looking for.
- Supported Field Types: Snippets and highlights are generated from fields such as Email, Text, Text Area, Text Area (Long), and Text Area (Rich). They are not generated from fields like Checkbox, Currency, Date, Date/Time, and others.
- Snippet Length: By default, each snippet displays up to approximately 300 characters. You can configure the snippet length between 50 and 1,000 characters using the
target_lengthparameter. For example, atarget_lengthof 120 characters is useful for displaying a snippet of approximately three lines of text in a standard mobile interface. - Limitations: Snippets are not generated for wildcard searches, when the search returns more than 20 results, or if the search term doesn’t appear in the first 6,000 characters of the field. Additionally, snippets may not be generated if an object contains more than 50 fields.
Example:
FIND {San Francisco} IN ALL FIELDS RETURNING KnowledgeArticleVersion (Id, Title WHERE PublishStatus = 'Online' AND Language = 'en_US') WITH SNIPPET(target_length=120)In this example, the SOSL query returns snippets for articles that match the search term “San Francisco,” with the target snippet length set to 120 characters.
By using the WITH SNIPPET clause, you can enhance the user experience by providing clear and concise excerpts that highlight the most relevant parts of the search results.
Visual Enhancement Filters
WITH HIGHLIGHT
Section titled “WITH HIGHLIGHT”The WITH HIGHLIGHT clause is an optional component in a SOSL query that highlights matching search terms with <mark> tags in the search results. This feature enhances the visibility of relevant content, making it easier for users to identify the information they are looking for.
Key Features:
- Supported Objects: The
WITH HIGHLIGHTclause can be used for searches involving business accounts, campaigns, contacts, custom objects, leads, opportunities, quotes, and users. - Supported Field Types: Highlighted search terms are generated from fields such as Auto Number, Email, Text, Text Area, and Text Area (Long). They are not generated from fields like Checkbox, Compound fields, Currency, Date, Date/Time, and others.
- Limitations: Search terms containing wildcards are not highlighted. Additionally, a maximum of 25 records per entity per SOSL query are highlighted.
- Corrected Spelling: If the original search term doesn’t yield any results due to incorrect spelling, the corrected spelling of the search term is highlighted in the results.
Example:
FIND {Salesforce West}IN ALL FIELDSRETURNING Building__c(Name, BuildingDescription__c)WITH HIGHLIGHTHere, the search term “Salesforce West” is highlighted in the custom field BuildingDescription__c of the custom object Building__c.
By using the WITH HIGHLIGHT clause, you can improve the user experience by making search results more visually accessible, helping users quickly locate the information they need.
Organizational Structure Filters
WITH DivisionFilter
Section titled “WITH DivisionFilter”The WITH DivisionFilter clause is an optional component in a SOSL query that filters search results based on division field values in organizations using the divisions feature. This allows you to target specific organizational segments, enhancing the precision of your search results. The clause pre-filters all records based on the specified division before applying other filters. You can specify a division by its name rather than by its ID, simplifying the process of targeting the desired division in your queries. Notably, all searches within a specific division also include the global division.
Example:
FIND {test} RETURNING Account (Id WHERE Name LIKE '%test%'), Contact (Id WHERE Name LIKE '%test%') WITH DIVISION = 'Global'In this example, the SOSL query searches for the term “test” within the specified division “Global,” returning results from both the Account and Contact objects.
By using the WITH DivisionFilter clause, you can effectively narrow down search results to specific divisions within your organization, improving the relevance and accuracy of the data retrieved.
WITH NETWORK
Section titled “WITH NETWORK”The WITH NETWORK clause is an optional component in a SOSL query that filters search results by Experience Cloud (Community) site ID, enabling searches within specific community contexts. This clause is particularly useful for targeting users and feeds associated with particular Experience Cloud sites.
Each Experience Cloud site is represented by a Network ID, and you can filter search results by specifying one or more Network IDs. For filtering by multiple sites, use WITH NETWORK IN ('NetworkId1', 'NetworkId2', ...), and for a single site, use WITH NETWORK = 'NetworkId'. For objects other than users and feeds, search results include matches across all Experience Cloud sites and internal company data, even if network filtering is applied.
Example:
FIND {test}RETURNING User (Id), FeedItem (Id, ParentId WHERE CreatedDate = THIS_YEAR ORDER BY CreatedDate DESC)WITH NETWORK IN ('NetworkId1', 'NetworkId2')This query searches multiple Experience Cloud sites for users and feed items containing the string “test,” sorting feed items from newest to oldest.
By using the WITH NETWORK clause, you can effectively narrow down search results to specific Experience Cloud sites, enhancing the relevance and accuracy of the data retrieved.
Commerce and Product Filtering
WITH PricebookId
Section titled “WITH PricebookId”The WITH PricebookId clause is an optional component in a SOSL query that filters product search results by a specific price book ID. This clause is applicable only to the Product2 object and is particularly useful for narrowing down product searches based on specific pricing structures.
Example:
FIND {laptop}RETURNING Product2WITH PricebookId = '01sxx0000002MffAAE'In this example, the SOSL query searches for products containing the term “laptop” within the specified price book, identified by the price book ID '01sxx0000002MffAAE'.
By using the WITH PricebookId clause, you can effectively filter product search results to align with specific pricing strategies, enhancing the precision and relevance of the data retrieved.
Search Behavior Controls
WITH SPELL_CORRECTION
Section titled “WITH SPELL_CORRECTION”The WITH SPELL_CORRECTION clause is an optional component in a SOSL query that controls automatic spell correction for search terms. By default, spell correction is enabled (set to true), which helps in correcting misspelled search terms to improve search results. However, disabling spell correction (setting it to false) can be useful for maintaining precise search results, especially for technical terms or proper nouns where exact spelling is crucial.
Example:
FIND {San Francisco}IN ALL FIELDSRETURNING AccountWITH SPELL_CORRECTION = falseIn this example, the SOSL query searches for the term “San Francisco” in all fields of the Account object, with spell correction disabled to ensure that the search results are based on the exact term provided.
By using the WITH SPELL_CORRECTION clause, you can tailor the search behavior to either accommodate common spelling errors or enforce strict spelling accuracy, depending on the needs of your query.
WITH METADATA
Section titled “WITH METADATA”The WITH METADATA clause is an optional component in a SOSL query that specifies whether additional metadata information is included in the search responses. By default, no metadata is returned. However, by using the LABELS value, you can include the display labels for the fields returned in the search results, providing more context and clarity.
Example:
FIND {Acme}RETURNING Account(Id, Name)WITH METADATA='LABELS'In this example, the SOSL query searches for the term “Acme” and returns results from the Account object, including the display labels for the Id and Name fields in the response.
By using the WITH METADATA clause, you can enhance the search results with additional context, making it easier to understand and interpret the data retrieved.
Analytics and Tracking Filters
The UPDATE VIEWSTAT and UPDATE TRACKING clauses are optional components in a SOSL query that allow you to monitor and report on Salesforce Knowledge article engagement and performance.
UPDATE VIEWSTAT
Section titled “UPDATE VIEWSTAT”The UPDATE VIEWSTAT clause is used to update the view statistics of Salesforce Knowledge articles. This helps determine how many times an article has been viewed, providing insights into article engagement. You can use the language attribute to search by a specific locale, but only one language can be specified per query. Use the Java locale format (e.g., en_US, fr_FR) to specify the language.
Example:
FIND {Title}RETURNING FAQ__kav (Title WHERE PublishStatus="Online" AND language="en_US" AND KnowledgeArticleVersion = 'ka230000000PCiy')UPDATE VIEWSTATIn this example, the SOSL query updates the view statistics for articles with the specified title in US English.
UPDATE TRACKING
Section titled “UPDATE TRACKING”The UPDATE TRACKING clause is used to track the keywords used in Salesforce Knowledge article searches. This allows developers to analyze search behavior and keyword usage. Similar to UPDATE VIEWSTAT, the language attribute can be used to specify the locale, with only one language per query.
Example:
FIND {Keyword}RETURNING KnowledgeArticleVersion (Title WHERE PublishStatus="Online" AND language="en_US")UPDATE TRACKINGIn this example, the SOSL query tracks the specified keyword used in article searches in US English.
Combining WITH Clauses
Section titled “Combining WITH Clauses”You can combine multiple WITH clauses in a single query to refine and enhance search results. For example, you might search for “customer support troubleshooting” across Knowledge articles and cases, applying data category filters, snippets, highlights, and network constraints.
These advanced filtering options enable precise, contextual, and enhanced search experiences across Salesforce data while maintaining performance and relevance.
Example Text Searches
Section titled “Example Text Searches”Here are some practical examples demonstrating how to construct and use SOSL queries:
FIND {Bingo}IN ALL FIELDSRETURNING Account(Name), Contact(FirstName, LastName)Searches for Bingo across all text fields within Account and Contact objects, returning specified fields. As this query is for the API, the search term is in curly brackets.
FIND 'New*'IN NAME FIELDSRETURNING Account(Name), Opportunity(Name, CloseDate)Searches for terms starting with New in name fields of Account and Opportunity objects, returning specified fields.
FIND {Jane AND Smith}IN ALL FIELDSRETURNING Contact(FirstName, LastName, Email)Searches for records containing both Jane and Smith in any text field of Contact objects, returning specified fields.
FIND {installation guide}IN ALL FIELDSRETURNING KnowledgeArticleVersion(Id, Title, Summary WHERE PublishStatus = 'Online')WITH SNIPPET(target_length=200)This query searches for the term installation guide across all text fields and returns results from the KnowledgeArticleVersion object, including the Id, Title, and Summary fields. The WITH SNIPPET clause generates contextual text excerpts with highlighted search terms, providing a snippet of 200 characters. This feature enhances the presentation of search results by offering a preview of the matched content.
Conclusion
Section titled “Conclusion”Salesforce Object Search Language (SOSL) offers a robust and flexible framework for performing text-based searches across multiple Salesforce objects. By understanding the syntax and components of SOSL queries, you can leverage its powerful capabilities to efficiently locate and retrieve data, even when the exact location is unknown. The various clauses, such as FIND, IN, RETURNING, and WITH, provide extensive customization options, allowing you to tailor searches to meet specific business needs.