Retrieving the Best Bets for SharePoint search programmatically based on a Search query

I have got a requirement to develop a Best Bets web part for SharePoint People Search as the default Search Best Bets does not work for People search. Well, will update on that later.

When I was looking for code on how to read the Best bets for a site programmatically I got it from this blog post. In this post I have enhanced that coding in order to filter the best bets collection by keywords term and synonyms term based on a search query using LINQ queries. Explanations are given in comments.

You need to have these 2 namespaces for LINQ query and IEnumerable collection that we are going to use.

using System.Linq;
using System.Collections.Generic;

Here is the complete code.

using (SPSite site = new SPSite("http://SharePointSite/"))
            {
                // get the proxy for the search service application
                    SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.
       GetProxy(SPServiceContext.GetContext(site));

                //get the Keywords collection for the site
                    Keywords keywords = new Keywords(proxy, new Uri(site.Url));

                //filter the keywords collection with Linq query and store it in an IEnumerable collection
                    IEnumerable<Keyword> Keywords = from Keyword keyword in keywords.AllKeywords
                                                    where keyword.Term.ToLower() == srchQuery.ToLower()  //checking for the terms equal to the search query
                                                    ||
                                                    (from Synonym c in keyword.Synonyms
                                                     where c.Term.ToLower() == srchQuery.ToLower()  // checking if synonyms are present for the search query
                                                     select c).Count() > 0

                                                    select keyword;

                    // loop through each keyword from the above collection
                    foreach (Keyword keyword in Keywords)
                    {
                        Console.WriteLine(keyword.Term);
                        foreach (BestBet bet in keyword.BestBets)
                        {
                            Console.WriteLine("\t{0} ({1})", bet.Title, bet.Url);
                        }
                    }
                }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s