コード例 #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string term = Request["q"];

        if (!IsPostBack && !string.IsNullOrEmpty(term))
        {
            txtSearchText.Text = term;
            string      indexName = string.Format("sitecore_{0}_index", Sitecore.Context.Database.Name);
            LuceneIndex index     = (LuceneIndex)ContentSearchManager.GetIndex(indexName);
            using (var searchContext = index.CreateSearchContext(Sitecore.ContentSearch.Security.SearchSecurityOptions.Default))
            {
                var results = GetSearchResults(term, searchContext);

                // Code for getting similar words or Did you mean
                string spellIndex = Settings.IndexFolder + "/custom_spellcheck_index";
                IndexSpellCheckDictionary(indexName, spellIndex);
                string[] suggestions = GetSuggestedWords(spellIndex, term, 3);
                ///

                bool hasNoResult = (results.Count < 1 && suggestions.Length > 0);
                if (hasNoResult)
                {
                    results = GetSearchResults(suggestions[0], searchContext);
                }

                if (results.Count() > 0)
                {
                    StringBuilder strSuggestion = new StringBuilder();
                    if (suggestions.Length > 0)
                    {
                        if (hasNoResult)
                        {
                            strSuggestion.Append("No results found for: <i>" + term + "</i><br/>Instead showing results for: ");
                        }
                        else
                        {
                            strSuggestion.Append("Did you mean? ");
                        }
                        lblDidYouMean.Text = strSuggestion.ToString();
                        foreach (string str in suggestions)
                        {
                            lblDidYouMean.Text += string.Format("<a href='?q={0}'>{0}</a> ", str);
                        }
                    }

                    repeaterResults.DataSource = results;
                    repeaterResults.DataBind();
                }
            }
        }
    }