The SOLR index is your quick access when it comes to Sitecore content and you can also extend this access by adding computed index fields. This is a way to enrich your searches with content that is not actually a part of your Sitecore template but is needed for quick searches.
You can use custom computed fields as per your requirement on fields like if you need a special formatted date and don’t want to recompile the code every time the format changes but you just want to change the configuration then there are various other reasons why you should use custom computed fields.
Please find below the steps to create a computed field on the code side.
To create a computed index field:
You need to create a patch config file for computed fields.
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultSolrIndexConfiguration type="Sitecore.ContentSearch.SolrProvider.SolrIndexConfiguration, Sitecore.ContentSearch.SolrProvider">
<documentOptions type="Sitecore.ContentSearch.DocumentBuilderOptions, Sitecore.ContentSearch">
<fields hint="raw:AddComputedIndexField">
<field fieldName="Date" referencedFieldName="__Updated" dateFormatPattern="yyyyMMdd" returnType="string">
xyz.Foundation.Search.ComputedFields.DateFormateField,xyz.Foundation.Search
</field>
</fields>
</documentOptions>
</defaultSolrIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
Then after we need to create ComputedFields Class and our logic in this class file.
namespace xyz.Foundation.Search.ComputedFields
{
public class DateFormateField : IComputedIndexField
{
public DateField(XmlNode configurationNode)
{
FieldName = XmlUtil.GetAttribute("fieldName", configurationNode);
ReferencedFieldName = XmlUtil.GetAttribute("referencedFieldName", configurationNode);
DateFormatPattern = ”yyyyMMdd”;
}
public string FieldName { get; set; }
public string ReferencedFieldName { get; set; }
public string DateFormatPattern { get; set; }
public virtual object ComputeFieldValue(IIndexable indexable)
{
var item = (SitecoreIndexableItem)indexable;
if (item?.Item == null)
{
Log.Error("DateField: indexable is not provided");
return string.Empty;
}
var field = (Sitecore.Data.Fields.DateField)item.Item.Fields[ReferencedFieldName];
if (field == null)
{
Log.Debug($"DateField: Cannot find field '{ReferencedFieldName}'");
return string.Empty;
}
return field.DateTime.ToString(DateFormatPattern, CultureInfo.InvariantCulture);
}
}
}