Wednesday, January 25, 2017

Apex - SOSL

Every business or application has search functionality as one of the basic requirements. For this, Salesforce.com provides two major approaches using SOSL and SOQL:

SOSL:
Searching the text string across the object and across the field will be done by using SOSL. This is Salesforce Object Search Language. It has capability of searching a particular string across the multiple object.
SOSL statements evaluate to a list of sObjects, where each list contains the search results for a particular sObject type. The result lists are always returned in the same order as they were specified in the SOSL query.
SOQL:
This is almost same as SOQL. You could use this to fetch the object records from one object only at a time. You could write nested queries and also fetch the records from parent or child object on which you are querying now.
We will be learning SOSL in this chapter. We will be exploring SOQL in next chapter.

SOSL Query Example

Consider a business case where we need to develop a program which could search a specified string. Suppose, we would like to search for string 'ABC' in Customer Name field of Invoice object. The code goes as follows:
First you have to create a single record in Invoice object with Customer name as 'ABC' so that we could get valid result when searched.
//Program To Search the given string in all Object
//List to hold the returned results of sObject generic type
List<list<SObject>> invoiceSearchList = new List<List<SObject>>();

//SOSL query which will search for 'ABC' string in Customer Name field of Invoice Object
invoiceSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice__c (Id,APEX_Customer__r.Name)];

//Returned result will be printed
System.debug('Search Result '+invoiceSearchList);

//Now suppose, you would like to search string 'ABC' in two objects, that is Invoice and Account. Then for this query goes like this:
//Program To Search the given string in Invoice and Account object, you could specify more objects if you want, create an Account with Name as ABC.
//List to hold the returned results of sObject generic type
List<List<SObject>> invoiceAndSearchList = new List<List<SObject>>();

//SOSL query which will search for 'ABC' string in Invoice and in Account object's fields
invoiceAndSearchList = [FIND 'ABC*' IN ALL FIELDS RETURNING APEX_Invoice__c (Id,APEX_Customer__r.Name), Account];

//Returned result will be printed
System.debug('Search Result '+invoiceAndSearchList);

//This list will hold the returned results for Invoice Object
APEX_Invoice__c [] searchedInvoice = ((List<APEX_Invoice__c>)invoiceAndSearchList[0]);

//This list will hold the returned results for Account Object
Account [] searchedAccount = ((List<Account>)invoiceAndSearchList[1]);
System.debug('Value of searchedInvoice'+searchedInvoice+'Value of searchedAc

No comments:

Post a Comment