Adding Suggestions to the SharePoint 2010 Search Programatically

There are numerous pages that show how to do this with PowerShell, but I found none on how to do it with plain old C#, so here it goes!

To abbreviate, I wanted to have SharePoint suggest the site collection user’s names after the first letters are filled in a search site’s search box. Here’s how I did it:

   1: //get the Search Service Application (replace with your own name)
   2: SearchServiceApplication searchApp = farm.Services.GetValue<SearchQueryAndSiteSettingsService>().Applications.GetValue<SearchServiceApplication>("Search Service Application") as SearchServiceApplication;
   3:   
   4: Ranking ranking = new Ranking(searchApp);
   5:  
   6: //replace EN-US with your language of choice
   7: LanguageResourcePhraseList suggestions = ranking.LanguageResources["EN-US"].QuerySuggestionsAlwaysSuggestList;
   8:  
   9: foreach (SPUser user in rootWeb.Users)
  10: {
  11:     suggestions.AddPhrase(user.Name, String.Empty);
  12: }
  13:  
  14: //get the job that processes suggestions and run it 
  15: SPJobDefinition job = SPFarm.Local.Services.OfType<SearchService>().SelectMany(x => x.JobDefinitions).Where(x => x.Name == "Prepare query suggestions").Single();
  16: job.RunNow();

You may do this, for example, on a feature. Of course, feel free to change users for something else, all suggestions are treated as pure text.

                             

3 Comments

Add a Comment

As it will appear on the website

Not displayed

Your website