Apex - SOSL

2019-10-26 16:26 更新

具有搜索功能是每個業(yè)務(wù)或應(yīng)用程序的基本要求之一。為此,Salesforce.com提供了使用SOSL和SOQL的兩種主要方法:


SOSL:

在整個對象和字段上搜索文本字符串將通過使用SOSL來完成。這是Salesforce對象搜索語言。它具有在多個對象上搜索特定字符串的能力。

SOSL語句評估sObjects的列表,其中每個列表包含特定sObject類型的搜索結(jié)果。結(jié)果列表始終以與在SOSL查詢中指定的順序相同的順序返回。


SOQL:

這與SOQL幾乎相同。您可以使用它從一個對象只獲取一次對象記錄。您可以編寫嵌套查詢,并從您要查詢的父對象或子對象獲取記錄。

我們將在本章中學(xué)習(xí)SOSL。我們將在下一章探討SOQL。


SOSL查詢示例

考慮一個商業(yè)案例,我們需要開發(fā)一個程序,可以搜索指定的字符串。假設(shè),我們想在Invoice對象的Customer Name字段中搜索字符串'ABC'。代碼如下:

首先,您必須在Invoice對象中創(chuàng)建一個客戶名為“ABC”的記錄,以便在搜索時獲得有效的結(jié)果。

//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 searchedAccount'+searchedAccount);

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號