Sitecore search: How to use Spell correction / suggestion in Sitecore with Lucene.NET


Recently our client asks us to extend the search feature with a spell check and provide suggestions. After some search I found some code that help me to bring the feature live. Thanks to tanasuk.

See the small method code here:

 public static String[] GetSpellCorrectionSuggestions(string searchTerm, int numberOfSuggestions = 5)

        {
            string[] suggestions = null;

            if (string.IsNullOrEmpty(searchTerm))

            {
                return null;
            }

            try
            {
                string indexPath = string.Format("{0}\\{1}\\", Sitecore.Configuration.Settings.IndexFolder, ConfigurationHelper.GetIndexName());
                Lucene.Net.Index.IndexReader reader = Lucene.Net.Index.IndexReader.Open(

                    FSDirectory.Open(indexPath), false);

                SpellChecker.Net.Search.Spell.SpellChecker speller =
                    new SpellChecker.Net.Search.Spell.SpellChecker(new RAMDirectory());

                speller.IndexDictionary(new LuceneDictionary(reader, "_title"));
                suggestions = speller.SuggestSimilar(searchTerm, numberOfSuggestions);
                reader.Dispose();
                return suggestions;
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(ex.Message, ex, Sitecore.Context.Item);
                return suggestions;
            }
        }

Comments