How to specify results source name for search query using SharePoint 2013 JavaScript Client Object Model

For using SharePoint 2013 search CSOM/JSOM there are already existing posts that explain how to perform search, gor example this or this

Today, however, I needed to set Results Source for my search query. You can do it using keywordQuery.set_sourceId(guid), but this requires GUID … and who likes dealing with GUIDs. Especially if you move configurations between environments.

I was able to peek into how Search Query Results webpart works, and it actually uses source name, this way making it possible to export/import webpart configuration.

As it turned out it was setting two query properties: SourceName and SourceLevel.

  • SourceName is obviously your source display name.
  • SourceLevel indicates the level at which given source was defined, with possible values:
    • SPWeb – sources defined locally for current web
    • SPSiteSubscription – sources defined for sote subscription (for SharePoint online this is the level where all your custom results sources are defined in tenant administration)
    • Ssa – search service application (for SharePoint Online all global predefined sources)

So for example to query “My Custom Source” defined in SharePoint Online admin center (tenancy) I could use the following code:

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

// 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

And you need to reference How you do that will depend on whether you are inside app, regular web or app web. For the master page on regular web just add script reference:

<script type="text/javascript" src="/_layouts/15/"></script>
This entry was posted in Sharepoint, SharePoint 2013. Bookmark the permalink.

Leave a Reply

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