Sitecore 7 Content Search – Custom Facets on List Fields

The search capabilities in Sitecore 7 are very impressive.  Built on Lucene and Solr, the search providers enable indexing and searching of content in Sitecore.  The first thing that came to mind when working on my first Sitecore 7 project was “how can I use values in a MultiList/TreeList field” to build facets for content authors. This post is the answer.

In my Sitecore project I had a product template with a Tree List field call Product Type.  Content authors used this field to assign one or more product types to the product item.  As we all know the list fields in Sitecore store the data in the fields a pipe delimited GUIDs, so I assumed that I would need to use some sort of computed field to retrieve a meaningful name for the index to facet on.

Step 1 was to create by computed field code.  For the sake of simplicity I decided to just store the Display Name of the item.

namespace Project.Web.Extensions
{

public class ProductType : IComputedIndexField

{

public string FieldName { get; set; }

public string ReturnType { get; set; }

public object ComputeFieldValue(IIndexable indexable)

{

Item item = indexable as SitecoreIndexableItem;

if (item == null)

{

return null;

}

var database = item.Database;

if (database == null)

{

return null;

}

Item obj = (Item)(indexable as SitecoreIndexableItem);

List<string> list = new List<string>();

string templateFieldName = templateFieldName = "Product Type";

if (field != null)

{

var items = field.GetItems();

foreach (var i in items)

{

list.Add(i.DisplayName);

}

return (object)list;

}

return null;

}

}

}

Step 2 was to add my new field to the Index.  As I was using Solr this was done in App_Config\Include\Sitecore.ContentSearch.Solr.Indexes.config.

<field fieldName=”producttype” returnType=”stringCollection”>Nlc.Web.Extensions. ProductType,Nlc.Web</field>

** Note.  In my tests the search providers to not work if the fieldname contains spaces.

Step 3 was to add the facet definition to the facet configurations at /sitecore/system/Settings/Buckets/Facets.  The Field Name entered in this location much match the field name used in the index setting in step 2.

Sitecore Facet Definition

One final note.  I did not update the actual Solr schema file, and Sitecore was able to work using the dynamic field mappings.  For a quick PoC I think this is fine, but I would update the schema in a production setting.

Advertisements

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 )

Google+ photo

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

Connecting to %s