---
title: "Search連絡先"
slug: "search-contacts"
abstract: "xConnect Client APIを使って連絡先を検索する方法。"
---
# Search連絡先

このトピックでは、連絡先にクエリを送る方法を紹介します。各例はclient.GetBatchEnumerator() / client.GetBatchEnumeratorSync() を使って [結果をページ化](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/paginatingxconnect-search-results.html "Paginating xConnect search results")しています。ジョインに依存する例には、ジョインをサポートしない検索プロバイダーに対してInteractionsCache面を使う同等の例があります。

> !注[xConnect検索のサポート方法一覧](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/supported-methods-and-operators-for-xconnect-search.html "Supported methods and operators for xConnect search") を参照してください。

## Search連絡先ID

IDによるSearchはサポートされていません。連絡先のIDが分かれば、[コレクションデータベースから連絡先を取得](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/work-with-contacts.html "Work with contacts")できます。

## 識別子、ソース、タイプで連絡先をSearch

識別子はxDBコレクションデータベースの暗号化されたフィールドに保存され、インデックス化されません。識別子のソースやタイプで検索するか、[識別子と識別子のソースを使ってxDBコレクションデータベースから連絡先を取得する](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/get-contacts.html "Get contacts")こともできます。

### 識別子ソースによる連絡先をSearch

以下の例は、Sourceプロパティの値がtwitterとなるすべての識別子を持つすべてのコンタクトを取得する方法を示しています。結果は10個ずつのバッチで返されます。各コンタクトに対して、元のtweeterを含む新しい識別子が追加され、古い識別子は削除されます(識別子は編集できません)。操作は約200件のバッチでxConnectに提出されます。

using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchBySource
 {
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> query = client.Contacts.Where(c => c.Identifiers.Any(s => s.Source == "twitter"));

 var enumerator = await query.GetBatchEnumerator(10);
 int counter = 0;

 // Cycle through batches
 while (await enumerator.MoveNext())
 {
 counter = counter + enumerator.Current.Count;

 // Cycle through batch of 10
 foreach (var contact in enumerator.Current)
 {
 var twitterIdentifiers = contact.Identifiers.Where(x => x.Source == "twitter");

 foreach (var identifier in twitterIdentifiers)
 {
 // Create new identifier where 'twitter' is replaced by 'tweeter'
 var newIdentifier = new ContactIdentifier("tweeter", identifier.Identifier, ContactIdentifierType.Known);

 // Add new identifier
 client.AddContactIdentifier(contact, newIdentifier);

 // Remove old identifier
 client.RemoveContactIdentifier(contact, identifier);
 }
 }

 if (counter == 100)
 {
 // Submit batch of approximately 200 operations (two operations per contact), reset counter
 // Some contacts might have more than one matching identifier
 await client.SubmitAsync();
 counter = 0;
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var enumerator = client.Contacts.Where(c => c.Identifiers.Any(s => s.Source == "twitter")).GetBatchEnumeratorSync(10);

 int counter = 0;

 // Cycle through batches
 while (enumerator.MoveNext())
 {
 counter = counter + enumerator.Current.Count;

 // Cycle through batch of 10
 foreach (var contact in enumerator.Current)
 {
 var twitterIdentifiers = contact.Identifiers.Where(x => x.Source == "twitter");

 foreach (var identifier in twitterIdentifiers)
 {
 // Create new identifier where 'twitter' is replaced by 'tweeter'
 var newIdentifier = new ContactIdentifier("tweeter", identifier.Identifier, ContactIdentifierType.Known);

 // Add new identifier
 client.AddContactIdentifier(contact, newIdentifier);

 // Remove old identifier
 client.RemoveContactIdentifier(contact, identifier);
 }
 }

 if (counter == 100)
 {
 // Submit batch of approximately 200 operations (two operations per contact), reset counter
 // Some contacts might have more than one matching identifier
 client.Submit();
 counter = 0;
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### 識別子タイプによるSearch Contact

以下の例では、少なくとも1つの既知の識別子を持つすべての接触が返されます。

using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByContactIdentifierType
 {
 public async void ExampleAsync()
 {
 using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var queryable = client.Contacts.Where(x => x.Identifiers.Any(i => i.IdentifierType == ContactIdentifierType.Known)).GetBatchEnumerator(10); // Get the first 10 results

 var enumerator = await queryable;

 // Total count of contacts (all batches)
 var totalContacts = enumerator.TotalCount;

 // Cycle through batches
 while (await enumerator.MoveNext())
 {
 // Cycle through batch of 10
 foreach (var contact in enumerator.Current)
 {
 // Do something with contact
 }
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 public void ExampleSync()
 {
 using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var enumerator = client.Contacts.Where(x => x.Identifiers.Any(i => i.IdentifierType == ContactIdentifierType.Known)).GetBatchEnumeratorSync(10); // Get the first 10 results

 // Total count of contacts (all batches)
 var totalContacts = enumerator.TotalCount;

 // Cycle through batches
 while (enumerator.MoveNext())
 {
 // Cycle through batch of 10
 foreach (var contact in enumerator.Current)
 {
 // Do something with contact
 }
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 }
}

## Search byファセットプロパティ価値

以下の例では、プロ **グラマーライター** という職種名の連絡先をすべて返送します。結果にファセスを含めるには、示された .WithExpandOptionsメソッドを使わなければなりません。

> !注PII機密データをインデックス化していなければ、PIIセンシティブとマークされたファセットやファセットプロパティで検索することはできません。例えば、連絡先のファーストネームと姓がPIIセンシティブとしてマークされています。

using Sitecore.XConnect.Collection.Model;
using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByFacet
 {
 // Async example
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.GetFacet<PersonalInformation>(Sitecore.XConnect.Collection.Model.CollectionModel.FacetKeys.PersonalInformation).JobTitle == "Programmer Writer")
 .WithExpandOptions(new ContactExpandOptions(PersonalInformation.DefaultFacetKey));

 var enumerator = await queryable.GetBatchEnumerator(10);

 while (await enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var name = contact.Personal().JobTitle; // Should be 'Programmer Writer'
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Sync example
 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.GetFacet<PersonalInformation>(Sitecore.XConnect.Collection.Model.CollectionModel.FacetKeys.PersonalInformation).JobTitle == "Programmer Writer")
 .WithExpandOptions(new ContactExpandOptions(PersonalInformation.DefaultFacetKey));

 var enumerator = queryable.GetBatchEnumeratorSync(10);

 while (enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var name = contact.Personal().JobTitle; // Should be 'Programmer Writer'
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### Search by Contact facetの存在

ヌル値の検索は不可能です。面が設定されているかどうかを判断するために、値を持ちやすい性質を探すべきです。例えば:

-   EmailAddressListクラスの構成者に希望するメールアドレスを渡す必要があります。したがって、入力されているPreferredEmail.SmtpAddressプロパティに頼ることができます。
-   PersonalInformationクラスには必須のプロパティはありません。したがって、設定されている可能性が最も高いプロパティを確認する必要があります。

以下の例では、EmailAddressListおよびPersonalInformation面を含むすべての連絡が返されます。この例は、連絡先の名前(PII機密データ)を検索できることに依存しています。

using Sitecore.XConnect.Collection.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByFacetExists
 {
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey).FirstName != string.Empty &&
 c.GetFacet<EmailAddressList>(EmailAddressList.DefaultFacetKey).PreferredEmail.SmtpAddress != string.Empty)
 .WithExpandOptions(new ContactExpandOptions(PersonalInformation.DefaultFacetKey));

 var enumerator = await queryable.GetBatchEnumerator(10);

 while (await enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var name = contact.Personal().JobTitle; // Should be 'Programmer Writer'
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey).FirstName != string.Empty &&
 c.GetFacet<EmailAddressList>(EmailAddressList.DefaultFacetKey).PreferredEmail.SmtpAddress != string.Empty)
 .WithExpandOptions(new ContactExpandOptions(PersonalInformation.DefaultFacetKey));

 var enumerator = queryable.GetBatchEnumeratorSync(10);

 while (enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var name = contact.Personal().JobTitle; // Should be 'Programmer Writer'
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### Search by nested facetプロパティ値

以下の例は、ブリストルに住所を持つすべての連絡先を返します。展開オプションを使ってAddressList面に結果を返します。

> !注AddressList.Preferred物件とAddressList.Others物件を確認しなければなりません。

using Sitecore.XConnect.Collection.Model;
using Sitecore.XConnect;
using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByFacetNested
 {
 // Async example
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts.Where(c => c.GetFacet<AddressList>(AddressList.DefaultFacetKey).Others.Any(a => a.Value.City == "Bristol") ||
 c.GetFacet<AddressList>(AddressList.DefaultFacetKey).PreferredAddress.City == "Bristol")
 .WithExpandOptions(new ContactExpandOptions(AddressList.DefaultFacetKey));

 var enumerator = await queryable.GetBatchEnumerator(10);

 while (await enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 // Check primary address
 var address = contact.Facets.OfType<AddressList>().Select(x => x.PreferredAddress).FirstOrDefault(f => f.City == "Bristol");

 // Check other addresses
 if (address == null)
 {
 address = contact.GetFacet<AddressList>(AddressList.DefaultFacetKey).Others.FirstOrDefault(x => x.Value.City == "Bristol").Value;
 }
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Sync example
 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts.Where(c => c.GetFacet<AddressList>(AddressList.DefaultFacetKey).Others.Any(a => a.Value.City == "Bristol") ||
 c.GetFacet<AddressList>(AddressList.DefaultFacetKey).PreferredAddress.City == "Bristol")
 .WithExpandOptions(new ContactExpandOptions(AddressList.DefaultFacetKey));

 var enumerator = queryable.GetBatchEnumeratorSync(10);

 while (enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 // Check primary address
 var address = contact.Facets.OfType<AddressList>().Select(x => x.PreferredAddress).FirstOrDefault(f => f.City == "Bristol");

 // Check other addresses
 if (address == null)
 {
 address = contact.GetFacet<AddressList>(AddressList.DefaultFacetKey).Others.FirstOrDefault(x => x.Value.City == "Bristol").Value;
 }
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### ファセット拡張法の使用

クエリの文脈でファセット拡張メソッドを使うことができます。以下の例は、.GetFacet<AddressList>メソッドと.Addresses()メソッドを使ってAddressListファセットを取得する方法を示しています。

// Without extension method
contact.GetFacet<AddressList>(AddressList.DefaultFacetKey);

// With extension method
contact.Addresses();

## Search by contactの行動

> !重要検索 [提供者が結合をサポートしている場合](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/work-with-search.html "Work with search")のみ、参加が可能です。ご自身の要件に合った例を使用してください。

接触検索とインタラクション検索を組み合わせて、特定の条件に合致する接触を返すことができます。相互作用を検索するには、[インタラクション検索](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/search-interactions.html "Search interactions")をご利用ください。

クエリは、クエリに一致するすべてのインタラクションを返します。しかし、expandオプションで返されたインタラクションは、必ずしもクエリのパラメータと一致しているわけではありません。

### Search by interaction date(交流日)で

以下の例は、5日を超えるインタラクションを持つコンタクトの取得方法を示しています。さらに、展開オプションを使ってコンタクトの上位20件のインタラクションを返します。これらのインタラクションは必ずしもクエリパラメータと一致しません。

#### ジョインズ付き

以下の例では、結合を用いて1つ以上の一致する相互作用との接触を得ます。

using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Documentation
{
 // ONLY APPLICABLE FOR SEARCH PROVIDERS
 // THAT SUPPORT JOINS
 public class SearchByInteractionDate
 {
 public async void Example()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.Interactions.Any(x => x.StartDateTime < DateTime.UtcNow.AddDays(-5)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerator = await queryable.GetBatchEnumerator(10);

 while (await enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var top20Interactions = contact.Interactions; // Contact's top 20 interactions - NOT LIMITED TO INTERACTIONS OLDER THAN FIVE DAYS
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.Interactions.Any(x => x.StartDateTime < DateTime.UtcNow.AddDays(-5)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerator = queryable.GetBatchEnumeratorSync(10);

 while (enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var top20Interactions = contact.Interactions; // Contact's top 20 interactions - NOT LIMITED TO INTERACTIONS OLDER THAN FIVE DAYS
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

#### ジョイントなし

以下の例では、InteractionsCacheファセットを使って1つ以上の一致する相互作用との接触を得ます。

using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using Sitecore.XConnect.Collection.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Documentation
{
 public class SearchByInteractionDateNoJoins
 {
 public async void Example()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.InteractionsCache().InteractionCaches.Any(x => x.StartDateTime < DateTime.UtcNow.AddDays(-5)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerator = await queryable.GetBatchEnumerator(10);

 while (await enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var top20Interactions = contact.Interactions; // Contact's top 20 interactions - NOT LIMITED TO THE LAST FIVE DAYS
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.InteractionsCache().InteractionCaches.Any(x => x.StartDateTime < DateTime.UtcNow.AddDays(-5)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerator = queryable.GetBatchEnumeratorSync(10);

 while (enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 var top20Interactions = contact.Interactions; // Contact's top 20 interactions - NOT LIMITED TO THE LAST FIVE DAYS
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### Search by interaction facets

以下の例は、特定のリファラーと相互作用するコンタクトの取得方法を示しています。

#### ジョインズ付き

以下の例では、結合を用いて1つ以上の一致する相互作用を持つ接触を取得します。

using Sitecore.XConnect.Collection.Model;
using System.Linq;
using Sitecore.XConnect;
using System.Collections.Generic;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByInteractionFacet
 {
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.Interactions.Any(x => x.WebVisit().Referrer == "google.com"))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerable = await queryable.GetBatchEnumerator(10);

 while (await enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contact
 }
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Sync example
 public void ExampleSync()
 {
 using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.Interactions.Any(x => x.WebVisit().Referrer == "google.com"))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerable = queryable.GetBatchEnumeratorSync(10);

 while (enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contact
 }
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }

#### ジョイントなし

以下の例では、InteractionsCacheファセットを使って1つ以上の一致する相互作用との接触を得ます。

using Sitecore.XConnect.Collection.Model;
using System.Linq;
using Sitecore.XConnect;
using System.Collections.Generic;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByInteractionFacetNoJoins
 {
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.InteractionsCache().Referrers.Any(r => r == "www.google.com"))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerable = await queryable.GetBatchEnumerator(10);

 while (await enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contact
 }
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Sync example
 public void ExampleSync()
 {
 using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.InteractionsCache().Referrers.Any(r => r == "www.google.com"))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20
 }
 });

 var enumerable = queryable.GetBatchEnumeratorSync(10);

 while (enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contact
 }
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### Search by interaction events(相互作用イベントによる検索)

以下の例は、以下の条件に合致するイベントを引き起こした連絡先の検索方法を示しています。

-   ここでイベントタイプは Goal
-   ここでイベント定義IDは {29408b2d-52b6-4f39-96ca-039cd96f4624}

#### ジョインズ付き

以下の例では、結合を用いて1つ以上の一致する相互作用を持つ接触を取得します。

using System;
using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByInteractionEventType
 {
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var goalGuid = Guid.Parse("29408b2d-52b6-4f39-96ca-039cd96f4624");

 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.Interactions.Any(f => f.Events.OfType<Goal>().Any(a => a.EngagementValue >= 50 && a.DefinitionId == goalGuid)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20 // Returns top 20 of all contact's interactions - interactions not affected by query
 }
 });

 var enumerable = await queryable.GetBatchEnumerator(10);

 while (await enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var goalGuid = Guid.Parse("29408b2d-52b6-4f39-96ca-039cd96f4624");

 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.Interactions.Any(f => f.Events.OfType<Goal>().Any(a => a.DefinitionId == goalGuid)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20 // Returns top 20 of all contact's interactions - interactions not affected by query
 }
 });

 var enumerable = queryable.GetBatchEnumeratorSync(10);

 while (enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

#### ジョイントなし

以下の例はInteractionsCache面を使用し、結合をサポートしないすべての検索プロバイダーでサポートされています。

using Sitecore.XConnect.Collection.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchByInteractionEventTypeNoJoins
 {
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var goalGuid = Guid.Parse("29408b2d-52b6-4f39-96ca-039cd96f4624");

 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.InteractionsCache().InteractionCaches.Any(i => i.Goals.Any(g => g.DefinitionId == goalGuid)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20 // Returns top 20 of all contact's interactions - interactions not affected by query
 }
 });

 var enumerable = await queryable.GetBatchEnumerator(10);

 while (await enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var goalGuid = Guid.Parse("29408b2d-52b6-4f39-96ca-039cd96f4624");

 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.InteractionsCache().InteractionCaches.Any(i => i.Goals.Any(g => g.DefinitionId == goalGuid)))
 .WithExpandOptions(new Sitecore.XConnect.ContactExpandOptions()
 {
 Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions()
 {
 Limit = 20 // Returns top 20 of all contact's interactions - interactions not affected by query
 }
 });

 var enumerable = queryable.GetBatchEnumeratorSync(10);

 while (enumerable.MoveNext())
 {
 foreach (var contact in enumerable.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

## 最近の活動によるSearch

EngagementMeasuresKeyBehaviorCacheは、連絡先の最近の行動に関する情報を格納する計算されたファセットです。これらのファセットをクエリする際には、両方ともコンタクトに属しているため、ジョインは必要ありません。以下の例は、EngagementMeasuresとKeyBehaviorCacheを使って、特定の基準セットに合致する最近の行動を持つコンタクトを返す方法を示しています。

### 関与措置

以下のクエリは、30秒以上の直近のやり取りがあったすべての連絡先を返します。

using Sitecore.XConnect.Collection.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchEngagementMeasures
 {
 // Async example
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var queryable = client.Contacts
 .Where(x => x.EngagementMeasures().AverageInteractionDuration > new TimeSpan(0, 0, 30))
 .WithExpandOptions(new ContactExpandOptions()
 {
 Interactions = new RelatedInteractionsExpandOptions()
 {
 Limit = 10
 }
 });

 var enumerator = await queryable.GetBatchEnumerator(10);

 while (await enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Sync example
 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var queryable = client.Contacts
 .Where(x => x.EngagementMeasures().AverageInteractionDuration > new TimeSpan(0, 0, 30))
 .WithExpandOptions(new ContactExpandOptions()
 {
 Interactions = new RelatedInteractionsExpandOptions()
 {
 Limit = 10
 }
 });

 var enumerator = queryable.GetBatchEnumeratorSync(10);

 while (enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### キービヘイビアキャッシュ

以下のクエリは、定義ID 951fb783-5959-49a4-a1f3-ced3453725a4の会場で最近行われたすべての接触を返します。

using Sitecore.XConnect.Collection.Model;
using System;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;
using System.Collections.Generic;

namespace Documentation
{
 public class SearchByKeyBehaviorCache
 {
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var venueId = Guid.Parse("951fb783-5959-49a4-a1f3-ced3453725a4");

 IAsyncQueryable<Contact> queryable = client.Contacts
 .Where(x => x.KeyBehaviorCache().Venues.Any(v => v.DefinitionId == venueId))
 .WithExpandOptions(new ContactExpandOptions()
 {
 Interactions = new RelatedInteractionsExpandOptions()
 {
 Limit = 1
 }
 });

 var enumerator = await queryable.GetBatchEnumerator(10);

 while (await enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var venueId = Guid.Parse("951fb783-5959-49a4-a1f3-ced3453725a4");

 IAsyncQueryable<Contact> queryable = client.Contacts
 .Where(x => x.KeyBehaviorCache().Venues.Any(v => v.DefinitionId == venueId))
 .WithExpandOptions(new ContactExpandOptions()
 {
 Interactions = new RelatedInteractionsExpandOptions()
 {
 Limit = 1
 }
 });

 var enumerator = queryable.GetBatchEnumeratorSync(10);

 while (enumerator.MoveNext())
 {
 foreach (var contact in enumerator.Current)
 {
 // Do something with contacts
 }
 }
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

## Search by expanded DateTimeプロパティ

Sitecore 10.0以降では、DateTime面プロパティにExpandDate属性を追加することで、DateTimeプロパティ全体の価値ではなく、日、月、年で検索できるようになっています。

以下の例は、PersonalInformation.Birthdateプロパティを使って9月に生まれたすべての連絡先を検索する方法を示しています:

var returnedContacts = await \_client.Contacts.Where(c => c.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey).Birthdate.Value.Month == 9).ToList();

PersonalInformation.Birthdateの性質はnullableです。nullableでない日付の場合は、.Value.Monthの代わりに .Monthを使用します。例えば:

// NOTE: Example assumes CustomFacet.CustomDateProperty has the ExpandDate attribute
var returnedContacts = await \_client.Contacts.Where(c => c.GetFacet<CustomFacet>(CustomFacet.DefaultFacetKey).CustomDateProperty.Month == 9).ToList();

## 部分的なテキスト検索

> !注部分的なテキスト検索は、xConnect検索においてSolrプロバイダーのみがサポートしています。

Sitecore 10.0以降では、単一のクエリで設定可能な連絡先ファセットリストに対して部分的なテキスト検索を行うことができます。Solrでは、名前、姓、メールアドレスなどのPersonalInformationファセットデータがデフォルトでtextmatchフィールドに追加されます。 [設定を拡張して追加のファセットを含める](https://doc.sitecore.com/xp/en/developers/101/platform-administration-and-architecture/en/configure-partial-search.html)ことも可能です。

以下の例は、名前、姓、またはメールアドレスが文字列Marで始まるすべての連絡先を返します。

IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(c => c.TextMatch("Mar"));

> !注特定の側面に対して部分的なテキスト検索を行うことはできません。

## 結果とページ付け

クエリの結果を返す推奨方法は、.GetBatchEnumerator() または .GetBatchEnumeratorSync() 拡張メソッドです。詳細は [ページングの概要](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/paginatingxconnect-search-results.html "Paginating xConnect search results") をご覧ください。

> !重要各メソッドごとに、単一バッチの最大サイズはSitecore.XConnect.SearchExtensions.DefaultBatchSizeにハードコードされており、1000に設定されています。この値は現在設定できません。

**非同期**

方法

注記

awaitclient.GetBatchEnumerator()

結果のページ付けの推奨方法。

awaitclient.ToSearchResults()

Skip()やTake()と組み合わせてバッチサイズを制御できます。総結果のカウントを返します。

awaitclient.ToList()

Skip()およびTake()と共に使用できます。連絡先一覧を返します。

**同期**

方法

注記

client.GetBatchEnumeratorSync()

結果のページ付けの推奨方法。

awaitclient.AsEnumerable()

Skip()とTake()で使用可能です。返すIEnumerable。

以下の例は、各メソッドを使って結果を返す方法を示しています:

using Sitecore.XConnect.Collection.Model;
using System.Collections.Generic;
using System.Linq;
using Sitecore.XConnect;
using Sitecore.XConnect.Client;

namespace Documentation
{
 public class SearchResults
 {
 // Async example
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts.Where(c => c.GetFacet<Sitecore.XConnect.Collection.Model.PersonalInformation>(CollectionModel.FacetKeys.PersonalInformation).FirstName == "Myrtle");

 // Option #1 - .ToSearchResults()
 SearchResults<Sitecore.XConnect.Contact> resultsOne = await queryable.ToSearchResults();

 var totalResults = resultsOne.Count; // Total results
 var contacts = resultsOne.Results.Select(x => x.Item); // Contacts
 var something = resultsOne.Results.Select(x => x.Score); // Scores

 // Option #2 - .ToSearchResults() with Skip()/Take()
 SearchResults<Sitecore.XConnect.Contact> resultsTwo = await queryable.Skip(10).Take(20).ToSearchResults();

 var totalResultsTwo = resultsTwo.Count; // Total results
 var contactsTwo = resultsTwo.Results.Select(x => x.Item); // Contacts - will be 20
 var scoresTwo = resultsTwo.Results.Select(x => x.Score); // Scores

 // Option #3 - .GetBatchEnumerator()
 var resultsThree = await queryable.GetBatchEnumerator(10);
 var totalResultsThree = resultsThree.TotalCount; // Count

 while (await resultsThree.MoveNext())
 {
 var contactsThree = resultsThree.Current; // Contacts
 }

 // Option #4 - .ToList()
 var resultsFour = await queryable.ToList();

 var contactsFour = resultsFour; // Contacts

 // Option #5 - .ToList() with Skip()/Take()
 var resultsFive = await queryable.Skip(10).Take(20).ToList();

 var contactsFive = resultsFive; // Contacts
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Async example
 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 IAsyncQueryable<Contact> queryable = client.Contacts.Where(c => c.GetFacet<Sitecore.XConnect.Collection.Model.PersonalInformation>(CollectionModel.FacetKeys.PersonalInformation).FirstName == "Myrtle");

 // Option #1
 // .ToSearchResults() not available as sync extension

 // Option #2
 // .ToSearchResults() not available as sync extension

 // Option #3 - .GetBatchEnumerator()
 var resultsThree = queryable.GetBatchEnumeratorSync(10);
 var totalResultsThree = resultsThree.TotalCount; // Count

 while (resultsThree.MoveNext())
 {
 var contactsThree = resultsThree.Current; // Contacts
 }

 // Option #4 - Can be used with :code:\`Skip()\` and :code:\`Take()\`
 var resultsFour = queryable.AsEnumerable();

 var contactsFour = resultsFour; // Contacts

 // Option #5 - .ToEnumerable() with Skip()/Take()
 var resultsFive = queryable.Skip(10).Take(20).AsEnumerable();

 var contactsFive = resultsFive; // Contacts
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

### 順番結果

結果はコンタクトのファセットやプロパティによって順序付けることができます。以下の例は、EngagementMeasuresファセットのMostRecentInteractionStartDateTimeプロパティでコンタクトを順序付けする方法を教えています。

IAsyncQueryable<Sitecore.XConnect.Contact> queryable = client.Contacts
 .Where(x => x.Interactions.Any())
 .OrderByDescending(x => x.EngagementMeasures().MostRecentInteractionStartDateTime)

> !注リストの性質で並べることはできません。例えば、連絡先のリストをその相互作用のStartDateTimeで並べることはできません。

## オプションを展開

.WithExpandOptions()メソッドを使って、各接触で返すべき面や関連する相互作用を指定します。これらの展開オプションは[、IDや識別子で連絡先を取得する](https://doc.sitecore.com/xp/ja/developers/105/sitecore-experience-platform/get-contacts.html "Get contacts")際に使うものと同じです。展開オプションを指定しなければ、接触面や関連する相互作用は返されません。

次の例では:

-   1つの接触面を回収中。
-   あるインタラクションの要素を取得中。
-   1回の接触につき最大3回までインタラクションを取得できます。

using Sitecore.XConnect.Collection.Model;
using Sitecore.XConnect;
using System.Linq;

namespace Documentation
{
 public class SearchResultsWithFacets
 {
 // Async
 public async void ExampleAsync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {

 IAsyncQueryable<Contact> query =
client.Contacts.Where(c => c.Interactions.Any(x => x.WebVisit().Browser
!= null))

                        .WithExpandOptions(new
ContactExpandOptions(AddressList.DefaultFacetKey)

                        {

                            Interactions = new
Sitecore.XConnect.RelatedInteractionsExpandOptions(WebVisit.DefaultFacetKey)

                            {
                                Limit = 30
                            }

                        });

 var results = await query.ToSearchResults();
 var contacts = await results.Results.Select(x => x.Item).ToList();

 foreach (var contact in contacts)
 {
 var interactions = contact.Interactions; // Maximum 3 interactions returned
 var interactionFacets = contact.Interactions.Where(x => x.WebVisit().Browser != String.Empty);
 var addressFacet = contact.Addresses(); // Contact address facet; using facet helper extension
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Sync
 public void Example()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 var query = client.Contacts.Where(c => c.Interactions.Any(x => x.WebVisit().Browser != null))
 .WithExpandOptions(new ContactExpandOptions(AddressList.DefaultFacetKey)
 {
 Interactions =
 new RelatedInteractionsExpandOptions(WebVisit.DefaultFacetKey)
 {
 Limit = 30
 }
 });

 var results = query.ToSearchResults().Result;
 var contacts = results.Results.Select(x => x.Item).ToList().Result;

 foreach (var contact in contacts)
 {
 var interactions = contact.Interactions; // Maximum 3 interactions returned
 var interactionFacets = contact.Interactions.Where(x => x.WebVisit().Browser != null);
 var addressFacet = contact.Addresses(); // Contact address facet; using facet helper extension
 }

 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}

> !注関連する相互作用の上限を1に指定することで、最新の相互作用のみが返されるようにします。

### 関連する相互作用はクエリの影響を受けません

以下のクエリは、WebVisitファセットを持つ少なくとも1つのインタラクションを持つすべてのコンタクトを返します。また、コンタクトの上位30回のインタラクションも返します。

client.Contacts.Where(c => c.Interactions.Any(x => x.WebVisit().Browser != null)).WithExpandOptions(new ContactExpandOptions(AddressList.DefaultFacetKey)
 {
 Interactions = new RelatedInteractionsExpandOptions(WebVisit.DefaultFacetKey)
 {
 Limit = 30
 }
 });

Interactionsコレクションはクエリの影響を受けません。クエリは任意の時点で少なくとも1つの一致する連絡先を持つすべての連絡先を返します。しかし、マッチに至る相互作用が必ずしもすべての連絡先のInteractionsプロパティに存在するわけではありません。

## カウントコンタクト

以下の方法で、接触データを返さずにすべての一致する接点のカウントを返します。

using System.Linq;
using Sitecore.XConnect;

namespace Documentation
{
 public class SearchResultsWithCount
 {
 // Async example
 public async void Example()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 int count = await client.Contacts.Where(c => c.Identifiers.Any(t => t.IdentifierType == Sitecore.XConnect.ContactIdentifierType.Known)).Count();
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }

 // Sync example
 public void ExampleSync()
 {
 using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
 {
 try
 {
 // There is no synchronous extension for Count - use SuspendContextLock instead
 int count = Sitecore.XConnect.Client.XConnectSynchronousExtensions.SuspendContextLock(client.Contacts.Where(c => c.Identifiers.Any(t => t.IdentifierType == Sitecore.XConnect.ContactIdentifierType.Known)).Count);
 }
 catch (XdbExecutionException ex)
 {
 // Handle exception
 }
 }
 }
 }
}