Example for SOSL(Salesforce Object Search Language)

Example for SOSL(Salesforce Object Search Language)

Examples:

Example 1:

FIND {test*} 
IN ALL FIELDS 
RETURNING Account (Id, Name), Contact, Opportunity, Lead

Searches field values starting with the keyword ‘test’ in all fields in Account, Contact, Opportunity, Lead and displays the result.

Example 2:

FIND {Test} 
IN Name FIELDS 
RETURNING Lead(Name WHERE CreatedDate = THIS_FISCAL_QUARTER LIMIT 10)

Searches Test in Name field in Lead with the condition CreatedDate is this fiscal quarter.

Sample SOSL:

FIND {test}
IN Name FIELDS
RETURNING
Account( Id, Name ), Contact( Id, Name )

Sample Apex Code:

String searchQuery = 'FIND {test} IN Name FIELDS RETURNING Account( Id, Name ), Contact( Id, Name )';
List < List < sObject > > searchResult = search.query( searchQuery );
List < Account > listAccount = ( List < Account > )searchResult.get( 0 );
List < Contact > listContact = ( List < Contact > )searchResult.get( 1 );
for ( Account acc : listAccount ) {
    
    System.debug( acc );
    
}
for ( Contact con : listContact ) {
    
    System.debug( con );
    
}

Leave a Reply