Skip to content

Instantly share code, notes, and snippets.

@mattbrailsford
Created March 5, 2019 13:16
Show Gist options
  • Save mattbrailsford/e76cf6b8acce1ffccbf65ab1fbfbd7cf to your computer and use it in GitHub Desktop.
Save mattbrailsford/e76cf6b8acce1ffccbf65ab1fbfbd7cf to your computer and use it in GitHub Desktop.
public class Bootstrap : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ExamineManager.Instance.IndexProviderCollection["ExternalIndexer"].GatheringNodeData += (sender, e) =>
{
// Extract JSON properties
var fieldKeys = e.Fields.Keys.ToArray();
foreach (var key in fieldKeys)
{
var value = e.Fields[key];
if (value.DetectIsJson())
{
IndexNestedObject(e.Fields, JsonConvert.DeserializeObject(value), key);
}
}
// Stuff all the fields into a single field for easier searching
var combinedFields = new StringBuilder();
foreach (var keyValuePair in e.Fields)
{
combinedFields.AppendLine(keyValuePair.Value);
}
e.Fields.Add("contents", combinedFields.ToString());
}
}
private void IndexNestedObject(Dictionary<string, string> fields, object obj, string prefix)
{
var objType = obj.GetType();
if (objType == typeof(JObject))
{
var jObj = obj as JObject;
if (jObj != null)
{
foreach (var kvp in jObj)
{
var propKey = prefix + "_" + kvp.Key;
var valueType = kvp.Value.GetType();
if (typeof(JContainer).IsAssignableFrom(valueType))
{
IndexNestedObject(fields, kvp.Value, propKey);
}
else
{
fields.Add(propKey, kvp.Value.ToString().StripHtml());
}
}
}
}
else if (objType == typeof(JArray))
{
var jArr = obj as JArray;
if (jArr != null)
{
for (var i = 0; i < jArr.Count; i++)
{
var itm = jArr[i];
var propKey = prefix + "_" + i;
var valueType = itm.GetType();
if (typeof(JContainer).IsAssignableFrom(valueType))
{
IndexNestedObject(fields, itm, propKey);
}
else
{
fields.Add(propKey, itm.ToString().StripHtml());
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment