NHibernate Search String Dictionary Bridge

NHibernate Search is an extension to NHibernate that uses Lucene to give you full text search using Lucene under the hood. It also makes using Lucene in your .NET app easier than using Lucene.NET directly.

Lucene only indexes text on a document in a flat key-value structure. Bridges are used to turn properties on your indexed documents into text.

NHibernate Search comes with bridges for common types such as enum, but you can also write your own. This is an example of a bridge that turns a Dictionary property on your indexed objects into a set of properties on the lucene document. It only works with a Dictionary<string, string>, but it wouldn't be much more difficult to make it work with a completely generic dictionary.

using System;

using System.Collections.Generic;
using Lucene.Net.Documents;
using NHibernate.Search.Bridge;

namespace NogginBox.Example.Search
{
    public class StringDictionaryBridge : IFieldBridge
    {
        public void Set(string name, object value, Document document, Field.Store store, Field.Index index, float? boost)
        {
            var ourDictionary = value as IDictionary<string, string>;

            if (ourDictionary == null)
            {
                throw new ArgumentException("StringDictionaryBridge can only index IDictionary<string, string>");
            }

            foreach (var prop in ourDictionary)
            {
                var propField = new Field($"{name}.{prop.Key}", prop.Value, store, index);
                if(boost.HasValue) propField.SetBoost(boost.Value);
                document.Add(propField);
            }
        }
    }
}