What is the return type of a SOSL search?

What is the return type of a SOSL search?

The return type of a SOSL search is List of List of sObjects.

Sample Code:

List<List<SObject>> searchList = [FIND ‘map*’ IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];
Account [] accounts = ((List<Account>)searchList[0]);
Contact [] contacts = ((List<Contact>)searchList[1]);
Opportunity [] opportunities = ((List<Opportunity>)searchList[2]);
Lead [] leads = ((List<Lead>)searchList[3]);

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