Apex-sosl

提供:Dev Guides
移動先:案内検索

Apex-SOSL

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

SOSL

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

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

SOSLクエリの例

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

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

//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については、次の章で説明します。