SOSL Example in Salesforce

SOSL Example in Salesforce

SOSL Example in Salesforce

What is SOSL in Salesforce?

Salesforce Object Search Language (SOSL) is a Salesforce search language that is used to perform text searches in records. Use SOSL to search fields across multiple standard and custom object records in Salesforce.  SOSL is a search language in salesforce and the important feature is that Unlike SOQL, we can search in multiple objects at same time using SOSL. In SOQL, we can query only one object at a time but in SOSL, We can search for some specified string like ‘testString’ in multiple objects at the same time.

  • We can search for some specified string like ‘testString’ in multiple objects at the same time.
  • We can mention in which fields of all the sObjects,we want to search for the string specified.
  • The SOSL query start with the keyword ‘FIND’.
  • You can specify, which fields to return for each object mentioned in SOSL query. Suppose you have performed search on three objects Account, Contact & Opportunity. Then you can mention like, for list returned with Account results only (Name, Industry) fields should come, and for Contacts results (firstName, lastName) should come and similarly for Opportunity.
  • The result of SOSL is a list of lists of sObjects “List<List<sObject>>”.
  • The returned result contains the list of sObjects in the same order as order mentioned in SOSL  query.
  • If a SOSL query does not return any records for a specified sObject type, then search results include an empty list for that sObject.
  • The search string should be at least two characters long.

Here is the quick demo SOSL Demo

SOSL-Example-in-Salesforce

Below is the sample code that has a input text box and a command button which will search for the entered string in three Object . i.e Accounts, Contacts, Opportunities and returned result will be shown in the page block tables.

SOSL Visualforce page

<apex:page controller="SOSLController">
  <apex:form >
  <apex:inputText value="{!searchStr}"/>
    <apex:commandButton value="Search in Account, Contact, Opportunity" action="{!soslDemo_method}"                reRender="acct,error,oppt,cont" status="actStatusId"/>
    <apex:actionStatus id="actStatusId">
                <apex:facet name="start" >
                    <img src="/img/loading.gif"/>                    
                </apex:facet>
    </apex:actionStatus>
  </apex:form>
 
    <apex:outputPanel title="" id="error">
     <apex:pageMessages ></apex:pageMessages>
     </apex:outputPanel>
 
    <apex:pageBlock title="Accounts" id="acct">
    <apex:pageblockTable value="{!accList }" var="acc">
          <apex:column value="{!acc.name}"/>
          <apex:column value="{!acc.Type}"/>
       </apex:pageblockTable>
    </apex:pageBlock>
 
 <apex:pageBlock title="Contacts" id="cont">
    <apex:pageblockTable value="{!conList}" var="con">
      <apex:column value="{!con.name}"/>
      <apex:column value="{!con.email}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
  
 <apex:pageBlock title="Opportunities" id="oppt">
    <apex:pageblockTable value="{!optyList}" var="opty">
      <apex:column value="{!opty.name}"/>
     <apex:column value="{!opty.StageName}"/>
 </apex:pageblockTable>
 </apex:pageBlock>
   
</apex:page>

SOSL Apex Controller

Public with sharing class SOSLController{
 Public List<Opportunity> optyList {get;set;}
 Public List<contact> conList{get;set;}
 Public List<account> accList{get;set;}
  
 Public String searchStr{get;set;}
   Public SOSLController(){
   }
  
  Public void soslDemo_method(){
   optyList = New List<Opportunity>();
   conList = New List<contact>();
   accList = New List<account>();
   if(searchStr.length() > 1){
   String searchStr1 = '*'+searchStr+'*';
   String searchQuery = 'FIND \'' + searchStr1 + '\' IN ALL FIELDS RETURNING  Account (Id,Name,type),Contact(name,email),Opportunity(name,StageName)';
   List<List <sObject>> searchList = search.query(searchQuery);
   accList = ((List<Account>)searchList[0]);
   conList  = ((List<contact>)searchList[1]);
   optyList = ((List<Opportunity>)searchList[2]);
   if(accList.size() == 0 && conList.size() == 0 && optyList.size() == 0){
       apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
       return;
   }
   }
   else{
   apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Please enter at least two characters..'));
   return;
   }
  }
}

Difference between SOQL and SOSL

Like SOQL, SOSL allows you to search your organization’s records for specific information. Unlike SOQL, which can only query one standard or custom object at a time, a single SOSL query can search all objects.

Another difference is that SOSL matches fields based on a word match while SOQL performs an exact match by default (when not using wildcards). For example, searching for ‘Digital’ in SOSL returns records whose field values are ‘Digital’ or ‘The Digital Company’, but SOQL returns only records with field values of ‘Digital’.

SOQL and SOSL are two separate languages with different syntax. Each language has a distinct use case:

  • Use SOQL to retrieve records for a single object.
  • Use SOSL to search fields across multiple objects. SOSL queries can search most text fields on an object.

For more information and possibilities in SOSL, please refer trailhead

Permanent link to this article: https://www.sfdcpoint.com/salesforce/sosl-example-in-salesforce/

2 comments

    • Rahul Khurana on May 14, 2014 at 1:52 pm
    • Reply

    Nice article.

    • Abilash K on January 14, 2015 at 9:13 pm
    • Reply

    The String searchStr1 = ‘*’+searchStr+’*’; used in the above code returns no output. Because the wildcard * can be used only in the middle or end of the string in salesforce.

    Hence, correct it as String searchStr1 = searchStr+’*’;

Leave a Reply

Your email address will not be published.