Tuesday, January 27, 2015

How to query using the Result Source name instead of using the id

I’m not going to take credit for this as the solution was originally blogged about at http://blog.voyta.net/2014/04/26/how-to-specify-results-source-name-for-search-query-using-sharepoint-2013-javascript-client-object-model/

I’ve known for some time that you can use the result source name in the .webpart config files as previously blogged. I just didn’t connect this over to SSOM/CSOM/REST for some reason. And turns out a colleague of mine stumbled upon the post referenced at the top for a solution without notifying me :).

There are two parts needed to get this working. Add a SourceName and a SourceLevel parameter. SourceName is obvious and takes the display name you have given your result source. SourceLevel takes any of the values below and has to match the level where you created your result source.
  • SSA
  • SPSiteSubscription
  • SPSite
  • SPWeb
Result sources created on the tenant level in SharePoint Online will use SPSiteSubscription.
The original post on this show JSOM code which is easily portable to CSOM.

var clientContext = new SP.ClientContext.get_current();
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(clientContext);
keywordQuery.set_queryText("*");

// set Source Name
keywordQuery.get_properties().set_item('SourceName', 'Test Global');
// set Source Level
keywordQuery.get_properties().set_item('SourceLevel', 'SPSiteSubscription');

var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(clientContext);
var searchResults = searchExecutor.executeQuery(keywordQuery);

clientContext.executeQueryAsync(function onSuccess() {
    // process searchResults
    // e.g. iterate through searchResults.get_value().ResultTables[0].ResultRows
}, function onFailure(args) {
    // process failure
});


If you however want to search in a RESTful manner, format your query by adding the source information needed to the properties property:

https://server/site/_api/search/query?querytext='*'&properties='SourceName:Your Source Name,SourceLevel:SPSite'

This beats using the &sourceid parameter with a guid any day, and allows you to move your search solutions across environments without a concern for the guid per environment.