Skip to content

Instantly share code, notes, and snippets.

@lowedown
Last active November 27, 2021 17:51
Show Gist options
  • Save lowedown/a2b24b1ae3267b022d1ba8b4c0397f6f to your computer and use it in GitHub Desktop.
Save lowedown/a2b24b1ae3267b022d1ba8b4c0397f6f to your computer and use it in GitHub Desktop.
Computed index field for Sitecore that indexes ContentHub assetIDs
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"
xmlns:set="http://www.sitecore.net/xmlconfig/set/"
xmlns:role="http://www.sitecore.net/xmlconfig/role/">
<sitecore>
<contentSearch>
<indexConfigurations>
<defaultSolrIndexConfiguration type="Sitecore.ContentSearch.SolrProvider.SolrIndexConfiguration, Sitecore.ContentSearch.SolrProvider">
<documentOptions type="Sitecore.ContentSearch.SolrProvider.SolrDocumentBuilderOptions, Sitecore.ContentSearch.SolrProvider">
<fields hint="raw:AddComputedIndexField">
<!-- Extracts ContentHub AssetIds from image fields -->
<field fieldName="contenthub_assetids" type="MyProject.ContentSearch.ContentHubImagesComputedField, MyProject" returnType="stringCollection">
</field>
</fields>
</documentOptions>
</defaultSolrIndexConfiguration>
</indexConfigurations>
</contentSearch>
</sitecore>
</configuration>
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.ComputedFields;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
namespace MyProject.ContentSearch
{
/// <summary>
/// Extracts ContentHub AssetIDs from image fields
/// </summary>
public class ContentHubImagesComputedField : AbstractComputedIndexField
{
public ContentHubImagesComputedField(XmlNode configNode) : base(configNode)
{
}
public override object ComputeFieldValue(IIndexable indexable)
{
Item item = indexable as SitecoreIndexableItem;
if (item == null)
{
return null;
}
IEnumerable<Field> imageFields = item.Fields.Where(f => f.TypeKey == "image");
if (!imageFields.Any())
{
return null;
}
List<string> assetIds = new List<string>();
foreach (Field imageField in imageFields)
{
string assetId = ((ImageField)imageField).GetAttribute("stylelabs-content-id");
if (!string.IsNullOrEmpty(assetId))
{
assetIds.Add(assetId);
}
}
return assetIds.Any() ? assetIds : null;
}
}
}
public class ContentHubImagesSearchResultItem : SearchResultItem
{
[IndexField("contenthub_assetids")]
public virtual IEnumerable<string> ContentHubAssetIds { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment