アペックス-SOSL

すべてのビジネスまたはアプリケーションには、基本的な要件の1つとして検索機能があります。このため、Salesforce.comは、SOSLとSOQLを使用した2つの主要なアプローチを提供します。この章では、SOSLアプローチについて詳しく説明します。

SOSL

オブジェクト全体およびフィールド全体のテキスト文字列の検索は、SOSLを使用して実行されます。これはSalesforceオブジェクト検索言語です。複数のオブジェクトにわたって特定の文字列を検索する機能があります。

SOSLステートメントはsObjectのリストに評価されます。各リストには、特定のsObjectタイプの検索結果が含まれています。結果リストは、常にSOSLクエリで指定されたのと同じ順序で返されます。

SOSLクエリの例

指定された文字列を検索できるプログラムを開発する必要があるビジネスケースを考えてみましょう。InvoiceオブジェクトのCustomerNameフィールドで文字列「ABC」を検索する必要があるとします。コードは次のようになります-

まず、検索時に有効な結果を取得できるように、顧客名を「ABC」としてInvoiceオブジェクトに単一のレコードを作成する必要があります。

// 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);

SOQL

これはSOQLとほぼ同じです。これを使用して、一度に1つのオブジェクトからのみオブジェクトレコードをフェッチできます。ネストされたクエリを記述し、現在クエリを実行している親オブジェクトまたは子オブジェクトからレコードをフェッチすることもできます。

次の章でSOQLについて説明します。