Adding Suggestions to the SharePoint 2010 Search Programatically

Posted by Ricardo Peres on ASP.net Weblogs See other posts from ASP.net Weblogs or by Ricardo Peres
Published on Thu, 01 Nov 2012 21:29:38 GMT Indexed on 2012/11/01 23:02 UTC
Read the original article Hit count: 375

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.

© ASP.net Weblogs or respective owner

Related posts about ASP.NET

Related posts about sharepoint