Create a computed index field
In simple indexing scenarios, an indexer takes a text and places it in an index. Sometimes you need more control over how the data is stored or, more importantly, what data is stored. You use computed fields to look up data and to use logic to specify what Sitecore stores in an index. For example, Sitecore uses computed fields to store the parsed Created Date of an item. A computed index field is processed for every Sitecore item that gets indexed.
To create a computed index field:
-
Create a class that implements the
Sitecore.ContentSearch.ComputedFields.IComputedIndexField
interface. -
Implement simple string properties named
FieldName
andReturnType
. TheFieldName
string is the name the field uses in the index. ThereturnType
string refers to the Solr data type that the Sitecore field type is mapped to withintypeMatches
. You can find all available return types listed under<typeMatches hint="raw:AddTypeMatch>
. -
Implement a method called
ComputeFieldValue()
. This method accepts an argument that implements theSitecore.ContentSearch.IIndexable
interface and that specifies the data to index. It returns an object that represents the value for the field.Your class will look like this example:
RequestResponsepublic class IsClone : IComputedIndexField { public object ComputeFieldValue(IIndexable indexable) { Item item = (Item) (indexable as SitecoreIndexableItem); return item.IsClone; } public string FieldName { get; set; } public string ReturnType { get; set; } }
NoteAvoid use of local variables. Sitecore reuses the same instance of the computed index field class. The
ComputeFieldValue(IIndexable)
method can be invoked simultaneously for the same computed index field with differentIIndexable
arguments. This might lead to inconsistent data in the search index or errors during indexing. If you cannot avoid the use of local variables, use[ThreadStatic]
or thread synchronization mechanisms. -
In the
Sitecore.ContentSearch.Solr.DefaultIndexConfiguration.config
configuration file, locate<fields hint="raw:AddComputedIndexField">
. You can read more about adding the computed field to the configuration. -
Add a
<field>
element toAddComputedIndexField
and reference your custom class and assembly within it. The computed field is mapped to a Solr dynamic field, for example:RequestResponse<fields hint="raw:AddComputedIndexField"> <field fieldName="nameOfComputedIndexField" returnType="string"> YourNamespaceHere.ComputedFields.IsClone, YourNamespaceHere </field> </fields>
TipThe example refers to the
IsClone
class defined in step 3 of this topic. The Sitecore computed fieldnameOfComputedIndexField
is mapped to the Solr string type field. -
Rebuild your search indexes using the Indexing Manager (accessed by opening the Indexing app from the control panel).