How To Programmatically Read Best Bets for SharePoint 2010 Search

For one of the projects I’m working on, I needed to be able to iterate search best bets programmatically. I did a quick Google search and came up with a blog post by Stefan Goßner on the subject. Turns out Stefan’s post was for SharePoint 2007 and the code uses a type that has been obsoleted. A little more Googling and I came up with the code for SharePoint 2010.
Here’s the code for a simple Console app you can use as a starting point if you need to do something similar.  You’ll need to add a reference to Microsoft.SharePoint.dll and Microsoft.Office.Server.Search.dll (which can be found in the ISAPI folder under the SharePoint system root). You’ll also need to set the build target to Any CPU.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server.Search.Administration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var site = new SPSite("<site collection url>");
            var proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.
                GetProxy(SPServiceContext.GetContext(site));
            var keywords = new Keywords(proxy, new Uri(site.Url));

            foreach (Keyword keyword in keywords.AllKeywords)
            {
                Console.WriteLine(keyword.Term);
                foreach (BestBet bet in keyword.BestBets)
                {
                    Console.WriteLine("\t{0} ({1})", bet.Title, bet.Url);
                }
            }
        }
    }
}

Comments