Friday, 24 March 2017

A Shortcut for Indexing Custom Sitecore xDB Facets

I recently read an article by Jonathan Robbins about indexing custom xDB facets. While following the instructions in his post I did a little research of my own and found a handy little shortcut.

As Jonathan's post explains, to index custom facet data you need to add a processor to the contactindexable.loadfields pipeline. The processor requires you to override the GetFields method. That's where you pull out data from the facet ready for indexing.

Typically, you'd create a series IndexableDataField objects one by one, specifying the index field name and the associated value. It's relatively simple, but it seems there's a lazier way...

IndexableDataField.CreateFromProperties

The IndexableDataField class has an abstract CreateFromProperties method. Simply pass it an object and it will return a collection IndexableDataField's.

The method has a few overloads, but here's the most useful:

CreateFromProperties<T>(T obj, string rootname, params string[] propertyNames)

obj
This is the facet object holding the data you want to index. CreateFromProperties is a generic method, so if you like you can use polymorphism to restrict which properties are read from the object.

rootname
This specifies a prefix for the index fields. For example, if you supply the rootname "contact" and the facet object has a Height property, then the resulting index field name will be "contact.Height". If you don't supply a rootname, then the index field wont have a prefix.

propertyNames
If you want to explicity specify which properties should be read from the facet object, you can supply a series of property names. If you don't specify any, then all properties are included.


Of course, you'll often want more granular control of how the IndexableDataField's are created. In those situations you can still just add them manually. But I think this way is a nice simple alternative.