SharePoint 2013 / 2010 : KeywordQuery Search Helper

Hello fellow SharePoint developers!

If I were to ask you how many of you were faced with a performance issues while retrieving data from SharePoint? I know I was, and not once! Throughout my years of SharePoint-related custom developing I developed a great fondness for SharePoint search – performance is a treat, and the main drawback of content visibility not being instant is hardly a show stopper in most scenarios.

Today, I’d like to share with you my helper class that I wrote to ease my SharePoint search query constructions.

It basically is a static class that hosts a number of methods, main being GetSearchResultsTable. This accepts several parameters:
1) int startRow – usually should be passed 0, unless you are anticipating that there could be more than 500 results, will cover that scenario below
2) string filter – this is what you’d type into a search box in SharePoint search center, leaving empty will return you all People results (feel free to edit the code to do otherwise)
3) out bool hasMoreResults – out parameter saying that there are more results to be retrieved, what to do in such case, I will cover below

First of all, here is the code:

You will notice I am using McmUlsLogging static class that basically writes into ULS log in 14/15 hive. I have a post about it in case you are interested in the code! Here it is: SharePoint 2013 / 2010: Custom ULS Logging provider

Now, in case you will get TRUE in out parameter – you have more results waiting to be grabbed. Reason for splitting – KeywordQuery class can only return 500 items per one call!
In this case you should query your items in a while loop, looping while you have TRUE in the out parameter, and calling the GetSearchResults method with start row being incremented by 500 in each iteration, Like this:

And that’s it, happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *