1. SOSL - Salesforce Object Search Language

  2. Used to perform text search in records.

  3. Use :

    1. SOQL - to retrieve records for a Single object.
    2. SOSL - to search fields across multiple objects.
  4. Syntax :

    FIND 'SearchQuery' [IN SearchGroup] [RETURNING ObjectsAndFields];
    
  5. SearchQuery

(a) Single Word

Should be enclosed in single Quotes.

(b) Phrase

Having multiple words and should be enclosed in double Quotes.

  1. SearchGroup
    1. SearchGroup is Optional.
    2. Default is ALL FIELDS.
    3. You can choose from the following.
      1. ALL FIELDS
      2. NAME FIELDS
      3. EMAIL FIELDS
      4. PHONE FIELDS
      5. SIDEBAR FIELDS
  2. ObjectsAndFields
    1. ObjectsAndFields is Optional.
      1. It is the Information to return in the Search Result - a list of one or more sObjects and within each sObject , list of one or more fields, with optional values to filter against.
      2. If not specified the search result contain the IDs of all objects found.
  3. Example :
	List<List<sObject>> qry = [FIND 'sanjay' RETURNING Account(Name), Contact(Name), Student__c(Name)];
		
		for (List<sObject> element : qry) {
			System.debug(element.getSObjectType());
			for (sObject item : element) {
				System.debug(item.get('Name'));
			}
		}
  1. Example
List<List<sObject>> qry = [FIND 'sanjay' IN NAME FIELDS RETURNING Account(Name), Contact(Name), Student__c(Name) LIMIT 4];
		

		List<Account> acc = new List<Account>();
		List<Contact> con = (List<Contact>) qry[1];
		List<Student__c> stu = (List<Student__c>) qry[2];
		acc = (List<Account>) qry[0];

		for (Account item : acc) {
			System.debug(acc.getSObjectType() + ' Name ' + item.Name);
		}

		for (Contact item : con) {
			System.debug(con.getSObjectType() + ' Name ' + item.Name + ' Email ' );
		}

		for (Student__c item : stu) {
			System.debug(stu.getSObjectType() + ' Name ' + item.Name);
		}