📜  Apex-SOSL

📅  最后修改于: 2020-11-05 03:15:32             🧑  作者: Mango


每个业务或应用程序都将搜索功能作为基本要求之一。为此,Salesforce.com提供了两种使用SOSL和SOQL的主要方法。让我们在本章中详细讨论SOSL方法。

SOSL

将使用SOSL在整个对象和整个字段中搜索文本字符串。这是Salesforce对象搜索语言。它具有跨多个对象搜索特定字符串的功能。

SOSL语句对一个sObject列表求值,其中,每个列表都包含特定sObject类型的搜索结果。结果列表始终以与SOSL查询中指定的顺序相同的顺序返回。

SOSL查询示例

考虑一个商业案例,其中,我们需要开发一个可以搜索指定字符串。假设我们需要在发票对象的“客户名称”字段中搜索字符串“ ABC”。代码如下-

首先,您必须在“发票”对象中创建一个客户名称为“ ABC”的单个记录,以便我们在搜索时可以获得有效的结果。

// Program To Search the given string in all Object
// List to hold the returned results of sObject generic type
List> invoiceSearchList = new List>();

// 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> invoiceAndSearchList = new List>();

// 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)invoiceAndSearchList[0]);

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

SOQL

这几乎与SOQL相同。您可以使用它一次仅从一个对象获取对象记录。您可以编写嵌套查询,还可以从正在查询的父对象或子对象中获取记录。

我们将在下一章中探讨SOQL。