IndexDictionary() public method

Indexes the data from the given IDictionary.
public IndexDictionary ( IDictionary dict ) : void
dict IDictionary dict the dictionary to index
return void
Example #1
0
        public static string[] SuggestSilmilarWords(string term, int count = 10)
        {
            IndexReader indexReader = IndexReader.Open(FSDirectory.Open(_luceneDir), true);

            // Create the SpellChecker
            var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(FSDirectory.Open(_luceneDir + "\\Spell"));

            // Create SpellChecker Index
            spellChecker.ClearIndex();
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, StronglyTyped.PropertyName <LuceneSearchModel>(x => x.Title)));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, StronglyTyped.PropertyName <LuceneSearchModel>(x => x.Description)));

            //Suggest Similar Words
            return(spellChecker.SuggestSimilar(term, count, null, null, true));
        }
Example #2
0
        private static void doSpellCheckerIndexing(string LuceneIndexDir, string SpellCheckerIndexDir)
        {
            try
            {
                // http://lucene.apache.org/java/2_2_0/api/org/apache/lucene/search/spell/SpellChecker.html
                FSDirectory spellCheckerIndexDir = FSDirectory.GetDirectory(SpellCheckerIndexDir, false);
                FSDirectory indexDir             = FSDirectory.GetDirectory(LuceneIndexDir, false);

                SpellChecker.Net.Search.Spell.SpellChecker spellchecker = new SpellChecker.Net.Search.Spell.SpellChecker(spellCheckerIndexDir);
                spellchecker.ClearIndex();
                // SpellChecker.Net.Search.Spell.SpellChecker spellchecker = new SpellChecker.Net.Search.Spell.SpellChecker (global::Lucene.Net.Store.Directory SpellChecker(spellIndexDirectory);

                IndexReader r = IndexReader.Open(indexDir);
                try
                {
                    // To index a field of a user index:
                    Dictionary dict = new SpellChecker.Net.Search.Spell.LuceneDictionary(r, "title");

                    spellchecker.IndexDictionary(dict);
                }
                finally
                {
                    r.Close();
                }
            }
            catch (Exception ex)
            {
                Console.Write("Could not create spell-checking index" + ex.Message);
            }
        }
Example #3
0
		private static void Main(string[] args)
		{
		    var ramDirectory = new RAMDirectory();
		    var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(ramDirectory);
		    var ms = new MemoryStream();
		    var sw = new StreamWriter(ms);
            sw.WriteLine("Book");
            sw.WriteLine("Bath");
            sw.WriteLine("Bed");
            sw.WriteLine("Make");
            sw.WriteLine("Model");
            sw.WriteLine("Vacum");
            sw.WriteLine("Wending machine");
            sw.Flush();
		    ms.Position = 0;
            spellChecker.setStringDistance(new JaroWinklerDistance());
            spellChecker.SetAccuracy(0.3f);
            spellChecker.IndexDictionary(new PlainTextDictionary(ms), CancellationToken.None);

		    var indexReader = IndexReader.Open(ramDirectory, true);
		    var termEnum = indexReader.Terms();
		    while (termEnum.Next())
		    {
		        Console.WriteLine(termEnum.Term);
		    }

		    var suggestSimilar = spellChecker.SuggestSimilar("both", 10);
		    foreach (var s in suggestSimilar)
		    {
		        Console.WriteLine(s);
		    }
		}
Example #4
0
        public void CreateFullTextIndex(IEnumerable <SearchResult> dataList, string path)
        {
            var directory = FSDirectory.Open(new DirectoryInfo(path));
            var analyzer  = new StandardAnalyzer(_version);

            //var analyzer = new WhitespaceAnalyzer();
            using (var writer = new IndexWriter(directory, analyzer, create: true, mfl: IndexWriter.MaxFieldLength.UNLIMITED))
            {
                foreach (var post in dataList)
                {
                    writer.AddDocument(MapPostToDocument(post));
                }

                writer.Optimize();
                writer.Commit();
                writer.Dispose();
                directory.Dispose();
                //change here
            }

            var indexReader = IndexReader.Open(FSDirectory.Open(path), readOnly: true);

            // Create the SpellChecker
            //Directory d = new Directory();d.Delete(path + "\\Spell");
            spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(FSDirectory.Open(path + "\\Spell"));

            // Create SpellChecker Index
            spellChecker.ClearIndex();
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Title"));
        }
Example #5
0
 private void EnsureIndexed()
 {
     if (!isIndexed)
     {
         checker.IndexDictionary(new LuceneDictionary(indexReader, "word"));
         isIndexed = true;
     }
 }
 private void EnsureIndexed()
 {
     if (!_isIndexed)
     {
         _checker.IndexDictionary(new LuceneDictionary(_indexReader, SpellCheckerConstants.SpellCheckerKey));
         _isIndexed = true;
     }
 }
Example #7
0
        //function to initialize the spell checker functionality
        public void SpellCheckerInit()
        {
            spellchecker = new SpellChecker.Net.Search.Spell.SpellChecker(spellCheckIndexStorage);

            // To index a field of a user index:
            indexReader = writer.GetReader();
            spellchecker.IndexDictionary(new LuceneDictionary(indexReader, WORD_FN));
        }
Example #8
0
        public static string[] SuggestSilmilarWords(string term, int count = 10)
        {
            IndexReader indexReader = IndexReader.Open(FSDirectory.Open(_luceneDir), true);

            // Create the SpellChecker
            var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(FSDirectory.Open(_luceneDir + "\\Spell"));

            // Create SpellChecker Index
            spellChecker.ClearIndex();
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Title"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Body"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "SubTitle"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Keywords"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Description"));

            //Suggest Similar Words
            return(spellChecker.SuggestSimilar(term, count, null, null, true));
        }
Example #9
0
		public void IndexWords() {
			// open the index reader
			IndexReader indexReader = IndexReader.Open(FSDirectory.Open(_indexRootDirectory), true);

			// create the spell checker
			var spell = new SpellChecker.Net.Search.Spell.SpellChecker(FSDirectory.Open(_spellRootDirectory));

			// add all the words in the field description to the spell checker
			spell.IndexDictionary(new LuceneDictionary(indexReader, "text"));
		}
Example #10
0
        public static Net.Search.Spell.SpellChecker GetSpellChecker(Directory luceneDir, Directory spellDir)
        {
            var indexReader = IndexReader.Open(luceneDir, true);

            var spell = new Net.Search.Spell.SpellChecker(spellDir);

            spell.IndexDictionary(new LuceneDictionary(indexReader, "name"));

            return(spell);
        }
Example #11
0
        /// <summary>
        /// Gets the similar words.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="word">The word.</param>
        /// <returns></returns>
        private static string[] SuggestSimilar(IndexReader reader, string fieldName, string word)
        {
            var spell = new SpellChecker.Net.Search.Spell.SpellChecker(reader.Directory());

            spell.IndexDictionary(new LuceneDictionary(reader, fieldName));
            var similarWords = spell.SuggestSimilar(word, 2);

            // now make sure to close the spell checker
            spell.Close();

            return(similarWords);
        }
Example #12
0
 public void TestSpellchecker()
 {
     SpellChecker.Net.Search.Spell.SpellChecker sc = new SpellChecker.Net.Search.Spell.SpellChecker(new RAMDirectory());
     indexReader = IndexReader.Open(store);
     sc.IndexDictionary(new LuceneDictionary(indexReader, "contents"));
     String[] suggestions = sc.SuggestSimilar("Tam", 1);
     AssertEquals(1, suggestions.Length);
     AssertEquals("Tom", suggestions[0]);
     suggestions = sc.SuggestSimilar("Jarry", 1);
     AssertEquals(1, suggestions.Length);
     AssertEquals("Jerry", suggestions[0]);
     indexReader.Close();
 }
    public void IndexSpellCheckDictionary(string dbIndexName, string spellIndex)
    {
        LuceneIndex index  = (LuceneIndex)ContentSearchManager.GetIndex(dbIndexName);
        IndexReader reader = index.CreateReader(LuceneIndexAccess.ReadOnly);

        FSDirectory dir   = FSDirectory.Open(spellIndex);
        var         spell = new SpellChecker.Net.Search.Spell.SpellChecker(dir);

        string           fieldName  = "description";
        LuceneDictionary dictionary = new LuceneDictionary(reader, fieldName);

        spell.IndexDictionary(dictionary, 10, 32);
    }
        public void TestBuild()
        {

            String LF = System.Environment.NewLine;
            String input = "oneword" + LF + "twoword" + LF + "threeword";
            PlainTextDictionary ptd = new PlainTextDictionary( new MemoryStream( System.Text.Encoding.UTF8.GetBytes(input)) );
            RAMDirectory ramDir = new RAMDirectory();
            SpellChecker.Net.Search.Spell.SpellChecker spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(ramDir);
            spellChecker.IndexDictionary(ptd);
            String[] similar = spellChecker.SuggestSimilar("treeword", 2);
            Assert.AreEqual(2, similar.Length);
            Assert.AreEqual(similar[0], "threeword");
            Assert.AreEqual(similar[1], "twoword");
        }
        public void TestBuild()
        {
            String LF                  = System.Environment.NewLine;
            String input               = "oneword" + LF + "twoword" + LF + "threeword";
            PlainTextDictionary ptd    = new PlainTextDictionary(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(input)));
            RAMDirectory        ramDir = new RAMDirectory();

            SpellChecker.Net.Search.Spell.SpellChecker spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(ramDir);
            spellChecker.IndexDictionary(ptd);
            String[] similar = spellChecker.SuggestSimilar("treeword", 2);
            Assert.AreEqual(2, similar.Length);
            Assert.AreEqual(similar[0], "threeword");
            Assert.AreEqual(similar[1], "twoword");
        }
Example #16
0
        static void MainV1_2()
        {
            var numberOfSuggestion = 100;

            var testFilePath       = @"../../../data/russianPosts.txt";
            var testDictionaryPath = @"../../../data/russian.dic";
            var testIndexPath      = @"../../../data/indexV1_2";
            var stopWordsPath      = @"../../../data/stopWords.txt";
            var outputFilePath     = @"../../../data/output.txt";

            var stopWordsSet = new HashSet <string>();

            using (var reader = new StreamReader(stopWordsPath))
            {
                while (!reader.EndOfStream)
                {
                    stopWordsSet.Add(reader.ReadLine());
                }
            }

            if (!File.Exists(testFilePath))
            {
                Console.WriteLine("Unpack the archive with the russian posts");
                Environment.Exit(1);
            }

            using (var reader = new StreamReader(testFilePath))
            {
                using (var writer = new StreamWriter(outputFilePath))
                {
                    var directory    = new SimpleFSDirectory(new DirectoryInfo(testIndexPath));
                    var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(directory);
                    spellChecker.IndexDictionary(new PlainTextDictionary(new FileInfo(testDictionaryPath)));

                    var analyzer = new StemmerCompareAnalyzer(stopWordsSet, spellChecker, numberOfSuggestion);

                    var stream = analyzer.TokenStream(null, reader);

                    while (stream.IncrementToken())
                    {
                        var sourceAttribute = stream.GetAttribute <ISourceAttribute>().Term;
                        var spellAttribute  = stream.GetAttribute <ISpellAttribute>().Term;
                        var stemAttribute   = stream.GetAttribute <IStemAttribute>().Term;

                        writer.WriteLine("{0, 20} {1, 20} {2, 20}", sourceAttribute, spellAttribute, stemAttribute);
                        //Console.WriteLine("{0, 20} {1, 20} {2, 20}", sourceAttribute, spellAttribute, stemAttribute);
                    }
                }
            }
        }
        public SuggestionQueryResult ExecuteSuggestionQuery(string indexName, SuggestionQuery suggestionQuery)
        {
            if (suggestionQuery == null) throw new ArgumentNullException("suggestionQuery");
            if (string.IsNullOrWhiteSpace(suggestionQuery.Term)) throw new ArgumentNullException("suggestionQuery.Term");
            if (string.IsNullOrWhiteSpace(indexName)) throw new ArgumentNullException("indexName");
            if (string.IsNullOrWhiteSpace(suggestionQuery.Field)) throw new ArgumentNullException("suggestionQuery.Field");
            if (suggestionQuery.MaxSuggestions <= 0) suggestionQuery.MaxSuggestions = 10;
            if (suggestionQuery.Accuracy <= 0 || suggestionQuery.Accuracy > 1) suggestionQuery.Accuracy = 0.5f;

            suggestionQuery.MaxSuggestions = Math.Min(suggestionQuery.MaxSuggestions,
                                                      _database.Configuration.MaxPageSize);

            var currentSearcher = _database.IndexStorage.GetCurrentIndexSearcher(indexName);
            IndexSearcher searcher;
            using(currentSearcher.Use(out searcher))
            {
                var indexReader = searcher.GetIndexReader();

                var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(new RAMDirectory(), GetStringDistance(suggestionQuery));
                try
                {
                    spellChecker.IndexDictionary(new LuceneDictionary(indexReader, suggestionQuery.Field));
                    spellChecker.SetAccuracy(suggestionQuery.Accuracy);

                    var suggestions = spellChecker.SuggestSimilar(suggestionQuery.Term, 
                        suggestionQuery.MaxSuggestions,
                        indexReader,
                        suggestionQuery.Field, 
                        true);

                    return new SuggestionQueryResult
                    {
                        Suggestions = suggestions
                    };
                }
                finally
                {
                    spellChecker.Close();
                    // this is really stupid, but it doesn't handle this in its close method!
                    GC.SuppressFinalize(spellChecker);
                }
            }
            
        }
Example #18
0
 public static void Build(string dictionaryPath, string indexPath)
 {
     var di = CreateTargetFolder(indexPath);
     using (var file = File.Open(dictionaryPath, FileMode.Open, FileAccess.Read))
     {
         var dict = new PlainTextDictionary(file);
         using (var staticSpellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(FSDirectory.Open(di)))
         {
             try
             {
                 staticSpellChecker.IndexDictionary(dict);
             }
             catch (Exception e)
             {
                 Console.WriteLine(e.Message);
             }
         }
     }
 }
Example #19
0
        static void MainV2()
        {
            var numberOfSuggestion = 100;

            var testFilePath       = @"C:/lucene/test1.txt";
            var testDictionaryPath = @"C:/lucene/ruStem.dict";
            var testIndexPath      = @"C:/lucene/indexV2";
            var stopWordsPath      = @"C:/lucene/stopWords.txt";

            var stopWordsSet = new HashSet <string>();

            using (var reader = new StreamReader(stopWordsPath))
            {
                while (!reader.EndOfStream)
                {
                    stopWordsSet.Add(reader.ReadLine());
                }
            }

            using (var reader = new StreamReader(testFilePath))
            {
                var directory    = new SimpleFSDirectory(new DirectoryInfo(testIndexPath));
                var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(directory);
                spellChecker.IndexDictionary(new PlainTextDictionary(new FileInfo(testDictionaryPath)));

                StringDistance getDist = spellChecker.GetStringDistance();

                var analyzer = new StemmerCompareAnalyzer(stopWordsSet, spellChecker, numberOfSuggestion);

                var stream = analyzer.TokenStream(null, reader);

                while (stream.IncrementToken())
                {
                    var termAttribute  = stream.GetAttribute <ITermAttribute>().Term;
                    var spellAttribute = stream.GetAttribute <ISpellAttribute>().Term;
                    var stemAttribute  = stream.GetAttribute <IStemAttribute>().Term;

                    Console.WriteLine("{0, 20} {1, 20} {2, 20}", termAttribute, spellAttribute, stemAttribute);
                }
            }
        }
Example #20
0
        public bool BuildDictionary()
        {
            try
            {
                IndexReader my_luceneReader = IndexReader.Open(Settings.Instance.StoreFolder, true);

                SpellChecker.Net.Search.Spell.SpellChecker spell = GetSpelling(true);
                if (spell != null)
                {
                    spell.IndexDictionary(new LuceneDictionary(my_luceneReader, IndexRecord.CONTENTFIELD));
                }
                my_luceneReader.Dispose();

                return(true);
            }
            catch (Exception ex)
            {
                GXLogging.Error(log, "BuildDictionary Error", ex);
                return(false);
            }
        }
Example #21
0
        public void SpellingSuggestion()
        {
            log.Debug("Building the word index");

            // Create a "Did you mean?" dictionary (the words are extracted from the search index)
            Directory wordDirectory = GetWordDirectory();

            Directory wordIndex = new RAMDirectory();

            SpellChecker.Net.Search.Spell.SpellChecker checker = new SpellChecker.Net.Search.Spell.SpellChecker(wordIndex);
            checker.ClearIndex();

            IndexReader reader = IndexReader.Open(wordDirectory);

            // Add words to spell checker index
            checker.IndexDictionary(new LuceneDictionary(reader, SpellChecker.Net.Search.Spell.SpellChecker.F_WORD));

            // Suggest similar words
            SuggestAndVerify(checker, "nhibrenate", "nhibernate");
            SuggestAndVerify(checker, "dreiven", "driven");
            SuggestAndVerify(checker, "inyection", "injection");
        }
Example #22
0
 /// <summary>
 /// Gets the similar words.
 /// </summary>
 /// <param name="fieldName">Name of the field.</param>
 /// <param name="word">The word.</param>
 /// <returns></returns>
 public string[] GetSimilarWords(string fieldName, string word)
 {
     SpellChecker.Net.Search.Spell.SpellChecker spell = new SpellChecker.Net.Search.Spell.SpellChecker(_IndexReader.Directory());
     spell.IndexDictionary(new LuceneDictionary(_IndexReader, fieldName));
     return(spell.SuggestSimilar(word, 2));
 }
 public void TestSpellchecker()
 {
     SpellChecker.Net.Search.Spell.SpellChecker sc = new SpellChecker.Net.Search.Spell.SpellChecker(new RAMDirectory());
     indexReader = IndexReader.Open(store);
     sc.IndexDictionary(new LuceneDictionary(indexReader, "contents"));
     String[] suggestions = sc.SuggestSimilar("Tam", 1);
     AssertEquals(1, suggestions.Length);
     AssertEquals("Tom", suggestions[0]);
     suggestions = sc.SuggestSimilar("Jarry", 1);
     AssertEquals(1, suggestions.Length);
     AssertEquals("Jerry", suggestions[0]);
     indexReader.Close();
 }
Example #24
0
        /// <summary>
        /// tek kelime seklinde girilmis bilgilerin dogrulugunu kontrol edip onerileni getirir
        /// </summary>
        /// <param name="word"></param>
        /// <returns></returns>
        private static Suggestion SpellCheck(string word)
        {
            var dir = new RAMDirectory();
            var iw  = new IndexWriter(dir, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED);

            var distDoc       = new Document();
            var textdistField = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED);

            distDoc.Add(textdistField);
            var iddistField = new Field("id", "", Field.Store.YES, Field.Index.NOT_ANALYZED);

            distDoc.Add(iddistField);

            textdistField.SetValue("Küçükyalı Kozyatağı");
            iddistField.SetValue("0");

            var countyDoc       = new Document();
            var textcountyField = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED);

            countyDoc.Add(textcountyField);
            var idcountyField = new Field("id", "", Field.Store.YES, Field.Index.NOT_ANALYZED);

            countyDoc.Add(idcountyField);

            textcountyField.SetValue("Maltepe Maslak");
            idcountyField.SetValue("1");

            var cityDoc       = new Document();
            var textcityField = new Field("text", "", Field.Store.YES, Field.Index.ANALYZED);

            cityDoc.Add(textcityField);
            var idcityField = new Field("id", "", Field.Store.YES, Field.Index.NOT_ANALYZED);

            cityDoc.Add(idcityField);

            textcityField.SetValue("İstanbul İzmir");
            idcityField.SetValue("2");

            iw.AddDocument(distDoc);
            iw.AddDocument(cityDoc);
            iw.AddDocument(countyDoc);

            iw.Commit();
            var reader = iw.GetReader();

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

            speller.IndexDictionary(new LuceneDictionary(reader, "text"));
            var suggestions = speller.SuggestSimilar(word, 5);

            var retVal = new Suggestion {
                SuggestedWord = suggestions.Length > 0 ? suggestions[0] : ""
            };

            var searcher = new IndexSearcher(reader);

            foreach (var doc in suggestions.Select(suggestion => searcher.Search(new TermQuery(new Term("text", suggestion)), null, Int32.MaxValue)).SelectMany(docs => docs.ScoreDocs))
            {
                switch (searcher.Doc(doc.Doc).Get("id"))
                {
                case "0":
                    retVal.SuggestedType = SuggestionType.District;
                    break;

                case "1":
                    retVal.SuggestedType = SuggestionType.County;
                    break;

                case "2":
                    retVal.SuggestedType = SuggestionType.City;
                    break;
                }
            }

            reader.Dispose();
            iw.Dispose();

            return(retVal);
        }
 public void Init(IndexReader reader)
 {
     spellChecker.IndexDictionary(new LuceneDictionary(reader, field), workContext.CancellationToken);
 }
        /// <summary>
        /// Gets the similar words.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="word">The word.</param>
        /// <returns></returns>
        private string[] SuggestSimilar(IndexReader reader, string fieldName, string word)
        {
            var spell = new SpellChecker(reader.Directory());
            spell.IndexDictionary(new LuceneDictionary(reader, fieldName));
            var similarWords = spell.SuggestSimilar(word, 2);

            // now make sure to close the spell checker
            spell.Close();

            return similarWords;
        }
Example #27
0
 public void Init(IndexReader reader)
 {
     spellChecker.IndexDictionary(new LuceneDictionary(reader, field));
 }
Example #28
0
        public static string[] SuggestSilmilarWords(string term, int count = 10)
        {
            IndexReader indexReader = IndexReader.Open(FSDirectory.Open(_luceneDir), true);

            // Create the SpellChecker
            var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(FSDirectory.Open(_luceneDir + "\\Spell"));

            // Create SpellChecker Index
            spellChecker.ClearIndex();
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Name"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Author"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Publisher"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "ISBN"));
            spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Description"));

            //Suggest Similar Words
            return spellChecker.SuggestSimilar(term, count, null, null, true);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            lastUpdatedText = SiteConfiguration.GetDictionaryText("Last Updated");
            cmdPrev.Text = SiteConfiguration.GetDictionaryText("Previous Button");
            cmdNext.Text = SiteConfiguration.GetDictionaryText("Next Button");

            // Decode the search string query string.  Will be empty string if no search string was provided.
            string searchStr = Server.UrlDecode(WebUtil.GetQueryString("searchStr"));

            // If the visitor provided no criteria, don't bother searching
            if (searchStr == string.Empty)
                lblSearchString.Text = SiteConfiguration.GetDictionaryText("Search Criteria") + SiteConfiguration.GetDictionaryText("No Criteria");
            else
            {
                string indexName = StringUtil.GetString(IndexName, SiteConfiguration.GetSiteSettingsItem()["Search Index"]);
                searchMgr = new SearchManager(indexName);

                // Remind the visitor what they provided as search criteria
                lblSearchString.Text = SiteConfiguration.GetDictionaryText("Search Criteria") + searchStr;

                // Perform the actual search
                searchMgr.Search(searchStr);

                // Display the search results
                results = searchMgr.SearchResults;

                // Now iterate over the number of results
                foreach (var result in results)
                {
                    Item hit = result.GetObject<Item>();
                    if (hit != null)
                    {
                        ResultsList.Add(hit);
                    }
                }

                // no results were found so we need to show message and suggestions
                if (searchMgr.SearchResults.Count == 0)
                {
                    Sitecore.Search.Index index = Sitecore.Search.SearchManager.GetIndex("system");
                    SpellChecker.Net.Search.Spell.SpellChecker spellchecker = new SpellChecker.Net.Search.Spell.SpellChecker(index.Directory);
                    spellchecker.IndexDictionary(new LuceneDictionary(IndexReader.Open(index.Directory), "_content"));
                    String[] suggestions = spellchecker.SuggestSimilar(searchStr, 5);

                    if (suggestions.Length > 0)
                    {
                        lblSearchString.Text += "<p>";
                        lblSearchString.Text += SiteConfiguration.GetDictionaryText("Did You Mean");
                        foreach (string s in suggestions)
                        {
                            lblSearchString.Text += String.Format("&nbsp;<a href=\"{0}?searchStr={1}\">{2}</a>&nbsp;", LinkManager.GetItemUrl(Sitecore.Context.Item), s, s);
                        }
                        lblSearchString.Text += "</p>";
                    }
                    else
                    {
                        string noResultsMsg = SiteConfiguration.GetDictionaryText("No Results");
                        LiteralControl noResults = new LiteralControl(string.Format("<p>{0}</p>", noResultsMsg));
                        pnResultsPanel.Controls.Add(noResults);
                    }
                }
                else
                {
                    if (!Page.IsPostBack)
                        DisplayResults();
                }
            }
        }
Example #30
0
        public virtual long CreateIndex()
        {
            try
            {
                var watch = new System.Diagnostics.Stopwatch();
                watch.Start();

                if (System.IO.Directory.Exists(_indexFilesPath))
                {
                    try
                    {
                        using (var directory = FSDirectory.Open(new DirectoryInfo(_indexFilesPath)))
                            directory.ClearLock(directory.GetLockId());
                    }
                    catch
                    {
                    }

                    FileUtils.DeleteDirRecursively(new DirectoryInfo(_indexFilesPath));
                }

                System.IO.Directory.CreateDirectory(_indexFilesPath);

                if (System.IO.Directory.Exists(_spellFilesPath))
                {
                    try
                    {
                        using (var directory = FSDirectory.Open(new DirectoryInfo(_spellFilesPath)))
                            directory.ClearLock(directory.GetLockId());
                    }
                    catch
                    {
                    }

                    FileUtils.DeleteDirRecursively(new DirectoryInfo(_spellFilesPath));
                }

                System.IO.Directory.CreateDirectory(_spellFilesPath);


                var allPosts = _postService.GetAsQueryable().Where(p => p.Published)
                               .Include(p => p.Descriptions)
                               .Include(p => p.Tags)
                               .Include(p => p.Categories);
                var languages = _languagesService.GetAsEnumerable();

                var analyzer = new StandardAnalyzer(Version);
                using (var directory = FSDirectory.Open(new DirectoryInfo(_indexFilesPath)))
                {
                    using (var writer =
                               new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED))
                    {
                        foreach (var post in allPosts)
                        {
                            writer.AddDocument(MapPost(post, post.PostType));//Default values

                            foreach (var language in languages.OrderByDescending(p => p.IsDefault))
                            {
                                var localizedMap = MapPost(post, language, post.PostType);
                                if (localizedMap != null)
                                {
                                    writer.AddDocument(localizedMap);    //Localized values
                                }
                            }
                        }

                        writer.Optimize();
                        writer.Commit();
                    }
                }

                using (var directory = FSDirectory.Open(new DirectoryInfo(_indexFilesPath)))
                {
                    using (var spellDirectory = FSDirectory.Open(new DirectoryInfo(_spellFilesPath)))
                    {
                        using (var indexReader = IndexReader.Open(directory, readOnly: true))
                        {
                            using (var spellChecker = new SpellChecker.Net.Search.Spell.SpellChecker(spellDirectory))
                            {
                                // Create SpellChecker Index
                                spellChecker.ClearIndex();
                                spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Title"));
                                spellChecker.IndexDictionary(new LuceneDictionary(indexReader, "Description"));

                                spellChecker.Close();
                            }
                        }
                    }
                }

                watch.Stop();

                MethodCache.ExpireTag(CacheTags.Search);

                return(watch.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                MethodCache.ExpireTag(CacheTags.Search);
                _eventPublisher.Publish(new CreateSearchIndexesFailEvent(e));
                throw;
            }
        }