Skip to content

Instantly share code, notes, and snippets.

@kgiszewski
Created October 5, 2017 20:48
Show Gist options
  • Save kgiszewski/aa48da36733aa05e1acddd167da2b99a to your computer and use it in GitHub Desktop.
Save kgiszewski/aa48da36733aa05e1acddd167da2b99a to your computer and use it in GitHub Desktop.
Archetype Examine Indexing
using System;
using System.Text;
using Archetype.Models;
using Examine;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Logging;
namespace Demo.Core.Events
{
public class ExamineMunger : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ExamineManager.Instance.IndexProviderCollection["ExternalIndexer"].GatheringNodeData += ExamineMunger_GatheringNodeData;
}
private void ExamineMunger_GatheringNodeData(object sender, IndexingNodeDataEventArgs nodeData)
{
try
{
var sb = new StringBuilder();
//now let's handle those darn harder property types like the page builder
if (nodeData.Fields.ContainsKey("modules"))
{
_handlePageBuilderModules(sb, nodeData);
}
_updateMungedField(nodeData, sb.ToString());
}
catch (Exception ex)
{
LogHelper.Info<ExamineMunger>(string.Format("Exception while munging nodeId: {0}", nodeData.NodeId));
LogHelper.Error<ExamineMunger>(ex.Message, ex);
}
}
private static void _handlePageBuilderModules(StringBuilder sb, IndexingNodeDataEventArgs nodeData)
{
var currentModuleAlias = string.Empty;
try
{
if (nodeData.Fields.ContainsKey("modules"))
{
var archetypeValueAsString = nodeData.Fields["modules"];
var modules = JsonConvert.DeserializeObject<ArchetypeModel>(archetypeValueAsString);
foreach (var module in modules)
{
currentModuleAlias = module.Alias;
switch (module.Alias)
{
case "richtext":
sb.Append(" " + _getSafeString(module, "headline"));
sb.Append(" " + _getSafeString(module, "text"));
break;
}
}
}
}
catch (Exception ex)
{
LogHelper.Info<ExamineMunger>(string.Format("Exception for current module type: {0}", currentModuleAlias));
LogHelper.Error<ExamineMunger>(ex.Message, ex);
}
}
//this method gets us a safe string to use without HTML
private static string _getSafeString(ArchetypeFieldsetModel module, string alias)
{
var value = module.GetValue<string>(alias);
if (value == null)
{
return string.Empty;
}
return value.StripHtml();
}
//this method updates our 'mungedField' that will be used in the searcher later
private static void _updateMungedField(IndexingNodeDataEventArgs nodeData, string value)
{
if (string.IsNullOrEmpty(value))
{
return;
}
if (nodeData.Fields.ContainsKey("mungedField"))
{
nodeData.Fields["mungedField"] += " " + value;
LogHelper.Info<ExamineMunger>(nodeData.Fields["nodeName"] + " - Updating...");
}
else
{
nodeData.Fields.Add("mungedField", value);
LogHelper.Info<ExamineMunger>(nodeData.Fields["nodeName"] + " - Creating...");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment