Skip to content

Instantly share code, notes, and snippets.

@RyanABailey
Created March 16, 2016 20:26
Show Gist options
  • Save RyanABailey/7937cb4455cadd061226 to your computer and use it in GitHub Desktop.
Save RyanABailey/7937cb4455cadd061226 to your computer and use it in GitHub Desktop.
Sitecore Lucene index datasource
namespace MyProject
{
/// <summary>
/// Index rendering/sublayout datasource
/// </summary>
public class IndexDataSource : IComputedIndexField
{
/// <inheritdoc />
public string FieldName { get; set; }
/// <inheritdoc />
public string ReturnType { get; set; }
/// <inheritdoc />
public object ComputeFieldValue(IIndexable indexable)
{
Item item = indexable as SitecoreIndexableItem;
if (item != null && !item.Paths.IsMediaItem) // Don't use this custom field on media items (PDFs)
{
var db = item.Database; // Can't use Sitecore.Context in searhc index
var indexedContent = string.Empty;
try
{
var allRenderings = item.Visualization.GetRenderings(Sitecore.Context.Device, true);
var filteredRenderings = allRenderings.Where(x => x.RenderingItem.Name == "Rich Text" && !string.IsNullOrEmpty(x.Settings.DataSource)); // Filter the renderings
if (filteredRenderings.Any())
{
foreach (var rendering in filteredRenderings)
{
var datasource = db.GetItem(new Sitecore.Data.ID(rendering.Settings.DataSource)); // Get the datasource
if (datasource != null)
{
var indexField = datasource.Fields["Text"]; // Field to index
if (indexField.HasValue)
{
indexedContent = indexedContent + Sitecore.StringUtil.RemoveTags(indexField.Value); // Concatenate content without HTML tags
}
}
}
return indexedContent;
}
}
catch (Exception)
{
return null;
}
}
return null; // Return null if nothing to index
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment