連絡先の検索

Version:
日本語翻訳に関する免責事項

このページの翻訳はAIによって自動的に行われました。可能な限り正確な翻訳を心掛けていますが、原文と異なる表現や解釈が含まれる場合があります。正確で公式な情報については、必ず英語の原文をご参照ください。

このトピックでは、連絡先をクエリする方法を示します。各例では、client.GetBatchEnumerator() / client.GetBatchEnumeratorSync() を使用して 結果をページ分割します。結合に依存する例には、結合をサポートしていない検索プロバイダーにInteractionsCacheファセットを使用する同等の例があります。

メモ

xConnect検索 でサポートされている方法のリスト を参照してください。

IDによる連絡先の検索

IDによる検索はサポートされていません。連絡先のIDがわかっている場合は、コレクション データベースから連絡先を取得できます

識別子のソースとタイプによる連絡先の検索

識別子はxDB Collectionデータベースの暗号化されたフィールドに保存され、インデックスは作成されません。識別子のソースまたはタイプで検索するか、識別子と識別子ソースを使用してxDB Collectionデータベースから連絡先を取得できます

識別子ソースによる連絡先の検索

次の例は、Sourceプロパティの値がtwitterである少なくとも1つの識別子を持つすべての連絡先を取得する方法を示しています。結果は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
                }
            }
        }
    }
}

識別子タイプによる連絡先の検索

次の例では、少なくとも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
                }
            }
        }

    }
}

ファセットプロパティ値による検索

次の例では、ジョブ タイトルがProgrammer Writerのすべての連絡先が返されます。結果にファセットを含めるには、次に示すように .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
                }
            }
        }
    }
}

コンタクトファセットの有無による検索

null値を検索することはできません。ファセットが設定されているかどうかを判断するには、値を持つ可能性が最も高いプロパティを検索する必要があります。例えば:

  • 優先メールアドレスは、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
                }
            }
        }
    }
}

ネストされたファセットプロパティ値による検索

次の例では、ブリストルに住所があるすべての連絡先を返します。展開オプションは、結果とともに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();

コンタクト行動による検索

大事な

結合は、検索プロバイダーが結合をサポートしている場合にのみ可能です。要件に適した例を使用してください。

コンタクト検索とインタラクション検索を組み合わせて、インタラクションが特定の条件に一致するコンタクトを返すことができます。インタラクションを検索するには、インタラクション検索を使用します。

クエリは、クエリに一致するインタラクションを持つすべての連絡先を返します。ただし、expandオプションを使用して返されるインタラクションは、必ずしもクエリパラメータと一致するとは限りません。

インタラクション日で検索

次の例は、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
                }
            }
        }
    }
}

インタラクションファセットによる検索

次の例は、特定のリファラーとインタラクションしたコンタクトを取得する方法を示しています。

結合あり

次の例では、結合を使用して、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
                }
            }
        }
    }
}

インタラクションイベントによる検索

次の例は、次の条件に一致するイベントをトリガーした連絡先を検索する方法を示しています。

  • イベントの種類の場所 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
                }
            }
        }
    }
}

最近のアクティビティから探す

EngagementMeasuresKeyBehaviorCacheは、コンタクトの最近の行動に関する情報を格納する計算されたファセットです。これらのファセットのクエリは、両方とも連絡先に属しているため、結合は必要ありません。次の例は、EngagementMeasuresKeyBehaviorCacheを使用して、最近の行動が特定の条件セットに一致する連絡先を返す方法を示しています。

エンゲージメント対策

次のクエリは、最近のインタラクションで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
                }
            }
        }
    }
}

拡張されたDateTimeプロパティによる検索

Sitecore 10.0以降では、ExpandDate属性をDateTimeファセット プロパティに追加して、DateTimeプロパティ値全体ではなく、日、月、年で検索できます。

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

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

PersonalInformation.Birthdateプロパティはnull許容です。null非許容の日付の場合は、.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();

部分テキスト検索

手記

パーシャル テキスト検索は、SolrプロバイダーのxConnect検索でのみサポートされています。

Sitecore 10.0以降では、1つのクエリでコンタクト ファセットの設定可能なリストに対して部分的なテキスト検索を実行できます。一部のPersonalInformationファセット・データ (名、姓、Eメール・アドレスなど) は、デフォルトでSolrのtextmatchフィールドに追加されます。 構成を拡張して、追加のファセットを含めることができます

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

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

特定のファセットに対して部分的なテキスト検索を実行することはできません。

結果とページネーション

.GetBatchEnumerator() または .GetBatchEnumeratorSync() 拡張メソッドは、クエリから結果を返すための推奨される方法です。詳細については、ページネーションの概要を参照してください。

大事な

各方法で、1つのバッチの最大サイズはSitecore.XConnect.SearchExtensions.DefaultBatchSizeにハードコードされ、1000に設定されます。この値は現在構成できません。

非同期

方式

筆記

awaitclient.GetBatchEnumerator()

結果をページ分割する推奨される方法。

awaitclient.ToSearchResults()

Skip()Take()と併用してバッチサイズを制御できます。合計結果の数を返します。

awaitclient.ToList()

Skip()Take()で使用できます。連絡先のリストを返します。

同期

方式

筆記

client.GetBatchEnumeratorSync()

結果をページ分割する推奨される方法。

awaitclient.AsEnumerable()

Skip()Take()で使用できます。IEnumerable<Contact>を返します。

次の例は、各メソッドを使用して結果を返す方法を示しています。

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または識別子で連絡先を取得するときに使用するオプションと同じです。展開オプションを指定しない場合、コンタクトファセットまたは関連するインタラクションは返されません。

次の例では、次のようになります。

  • 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
                }
            }
        }
    }
}
この記事を改善するための提案がある場合は、 お知らせください!