xConnect: Searching for Contacts in Sitecore 9

In previous posts, xConnect was introduced, Contacts were added to xDB and a custom model was deployed. But what about searching for existing contacts? Let’s take a look at a couple of examples!

Searching for Multiple Contacts

In this example, we’re going to search for any Contacts who have had Interactions recorded in the past 30 days.

private static XConnectClient GetClient()
{
    var config = new XConnectClientConfiguration(
        new XdbRuntimeModel(CollectionModel.Model),
        new Uri("https://sc9_xconnect"),
        new Uri("https://sc9_xconnect"));

    try
    {
        config.Initialize();
    }
    catch (XdbModelConflictException ex)
    {
        Console.WriteLine(ex.Message);
        throw;
    }

    return new XConnectClient(config);
}

private static async void SearchContacts()
{
    using (var client = GetClient())
    {
        var queryable = client.Contacts
            .Where(c => c.Interactions.Any(x => x.StartDateTime > DateTime.UtcNow.AddDays(-30)))
            .WithExpandOptions(new ContactExpandOptions( "Personal" ));

        var results = await queryable.ToSearchResults();
        var contacts = await results.Results.Select(x => x.Item).ToList();
        foreach (var contact in contacts)
        {
            Console.WriteLine($"{contact.Personal().FirstName} {contact.Personal().LastName}");
        }
    }
}

One particular call I’d like to point out is the WithExpandOptions method. When retrieving data through xConnect, you need to specify what facets you’d like returned with your results, otherwise you’ll only get the Identifiers collection.

Retrieving a Single Contact

If you know an identifier for the particular Contact you’d like to retrieve from xDB, you can go straight to the Collections database.

using (var client = GetClient())
{
    var contactReference = new IdentifiedContactReference("twitter", "longhorntaco");
    var contact = client.Get(contactReference, new ExpandOptions() { FacetKeys = { "Personal" } });

    if (contact != null)
    {
        Console.WriteLine($"{contact.Personal().FirstName} {contact.Personal().LastName}");
    }
}

Again, we need to specify, through the use of ExpandOptions, which facets we want returned with the Contact.

_**NOTE: When retrieving a Contact from the Collections database, you need to specify the Identifier AND the Identifier Source._

Source code can be found on GitHub.

Happy Sitecore trails, my friend!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: