Examine - Cannot add custom index field for MediaType

Umbraco 7.2.6

Am trying to add a custom field to a custom Index using the Examine GatheringNodeData event. The data is coming from a nuPicker property on the Image MediaType.

When I click Save on a media item, the code runs, I have stepped through it and the field tagKey is added with the correct data (a number as string in this case) to the e.Fields collection.

After iterating the collection I use

e.Fields.Add("tagKey", tagKey.ToString());

which should add the field to the index.

If I click Save on the media item again I would expect to see the extra field in e.Fields when stepping through this code but nothing.

I have checked the Index in Luke but I cannot see the tagKey field which should contain something like 12343 12322 12366… but nothing

Here’s the code:

namespace site.web.EventHandlers
{
    public class ExamineEventHandler : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication,
            ApplicationContext applicationContext)
        {
            ExamineManager.Instance.IndexProviderCollection["TagIndexer"].GatheringNodeData +=ExamineEventHandler_GatheringNodeData;
        }

        private void ExamineEventHandler_GatheringNodeData(object sender, IndexingNodeDataEventArgs e)
        {
            // Only process mediaTypes
            if(e.IndexType != UmbracoExamine.IndexTypes.Media) 
                return;

            var fields = e.Fields;

            var tagKey = new StringBuilder();

            foreach (var field in fields)
            {
                if (field.Key == "imageTags")
                {
                    if (!string.IsNullOrEmpty(field.Value))
                    {
                        // Get media tags from nuPicker
                        var mediaTags = JsonConvert.DeserializeObject<List<NuPickerValueModel>>(field.Value);

                        // Build tag field content
                        foreach (var tag in mediaTags)
                        {
                            tagKey.Append(tag.key + " ");
                        }
                    }
                    break;
                }
            }
            // Remove custom tag fields (This method does not find the tagKey field)
            RemoveTagFields(e);

            // Add field to index
            e.Fields.Add("tagKey", tagKey.ToString());
        }

        private void RemoveTagFields(IndexingNodeDataEventArgs e)
        {
            if (e.Fields.ContainsKey("tagKey"))
            {
                e.Fields.Remove("tagKey");
            }
        }
    }

}

This is a companion discussion topic for the original entry at https://our.umbraco.com/forum/72892-examine-cannot-add-custom-index-field-for-mediatype