How to: Query Search with the SharePoint 2013 JavaScript Client Object Model
Posted
Thursday, April 18, 2013 10:08 PM
by
CoreyRoth
As a developer, if you have ever looked for information on how to query search in SharePoint, there is a good chance that you have ran into one of my articles. I’ve been writing about how to query search in a variety of different ways since 2007. They have always been some of the most popular articles on my site. SharePoint 2013 has so many new ways to query search, it has taken me time to write up all of the different ways. I am keeping the tradition alive by writing about how to query using the JavaScript Client Object Model provided by SP.Search.js. You may have already seen my post on how to query from JavaScript and REST or my post on how to use the managed CSOM to Query Search. You’ll find that querying from JavaScript looks very similar to the managed side of things. In fact even the namespaces are the same and most of the code is quite similar between C# and JavaScript. However, there are some nuances due to JavaScript so I wanted to share a complete code sample.
I am going to build my example inside a SharePoint-hosted app. If you’re not familiar with that process yet, take a look at my Client Web Part post to get started. When it comes to apps, you need to be sure and request permission to access search. Do this by editing your AppManifest.xml and clicking on the permissions tab. Select Search and then select QueryAsUserIgnoreAppPrincipal. If you forget this step, you won’t get an error, your queries will simply just return zero results.
I’m going to put all of my code in the welcome page today. My default.aspx page will have the same HTML as my other JavaScript post. I simply add a textbox, a button, and a div to hold the results. The user will type in his or her query, click the button, and then see search results.
<div>
<label for="searchTextBox">Search: </label>
<input id="searchTextBox" type="text" />
<input id="searchButton" type="button" value="Search" />
</div>
<div id="resultsDiv">
</div>
We’re going to edit App.js next. Since we’re in an App, I am assuming you already have code to get the SharePoint context since Visual Studio adds it for you. If not, you can get it like this.
var context = SP.ClientContext.get_current();
I then add a click event handler to my document ready function.
$("#searchButton").click(function () {
});
In here, we’ll put our code to get a KeywordQuery and SearchExecutor object to execute our query in a similar manner to the Managed CSOM approach. Now, we need to get our KeywordQuery object using the context object we already have.
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
Then, we set the query text using the value the user entered in the textbox with set_queryText().
keywordQuery.set_queryText($("#searchTextBox").val());
Now, we just need to create a SearchExecutor object and execute the query. I am assigning the results of the query back to a global variable called results. Since apps by default have ‘use strict’ enabled, you need to be sure and declare this first.
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
results = searchExecutor.executeQuery(keywordQuery);
Then like any CSOM code, we have to use executeQueryAsync to make the actual call to the server. I pass it methods for success and failure.
context.executeQueryAsync(onQuerySuccess, onQueryError);
I generally prefer using REST to do my search queries. However, when it comes to processing results, the data we get back from CSOM is typed better and much easier to access. This results in less code that we have to deal with. You can get quite a bit of data back such as the number of results returned just by exmaining results.m_value. Each individual result can be found in results.m_value.ResultTables[0].ResultRows. The managed properties of each row are typed directly on the object so that it means you can access them directly if you know the name (i.e.: Author, Write, etc). Iterating the values is simple using $.each. Take a look at my example where I am writing the values into an HTML table.
function onQuerySuccess() {
$("#resultsDiv").append('<table>');
$.each(results.m_value.ResultTables[0].ResultRows, function () {
$("#resultsDiv").append('<tr>');
$("#resultsDiv").append('<td>' + this.Title + '</td>');
$("#resultsDiv").append('<td>' + this.Path + '</td>');
$("#resultsDiv").append('<td>' + this.Author + '</td>');
$("#resultsDiv").append('<td>' + this.Write + '</td>');
$("#resultsDiv").append('</tr>');
});
$("#resultsDiv").append('</table>');
}
The last thing to implement is the code to handle errors. It just sends the error to an alert dialog.
function onQueryFail(sender, args) {
alert('Query failed. Error:' + args.get_message());
}
When we run the app, it will look something like this.
Executing a query will show us the four columns I specified in my $.each statement.
Pretty easy, right? Here is the entire code snippet of my App.js.
'use strict';
var results;
var context = SP.ClientContext.get_current();
var user = context.get_web().get_currentUser();
// This code runs when the DOM is ready and creates a context object which is needed to use the SharePoint object model
$(document).ready(function () {
$("#searchButton").click(function () {
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
keywordQuery.set_queryText($("#searchTextBox").val());
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
results = searchExecutor.executeQuery(keywordQuery);
context.executeQueryAsync(onQuerySuccess, onQueryFail)
});
});
function onQuerySuccess() {
$("#resultsDiv").append('<table>');
$.each(results.m_value.ResultTables[0].ResultRows, function () {
$("#resultsDiv").append('<tr>');
$("#resultsDiv").append('<td>' + this.Title + '</td>');
$("#resultsDiv").append('<td>' + this.Author + '</td>');
$("#resultsDiv").append('<td>' + this.Write + '</td>');
$("#resultsDiv").append('<td>' + this.Path + '</td>');
$("#resultsDiv").append('</tr>');
});
$("#resultsDiv").append('</table>');
}
function onQueryFail(sender, args) {
alert('Query failed. Error:' + args.get_message());
}
Although, I typically prefer the REST interface for querying search. I have to admit, I like the ease of working with the results in CSOM. Hopefully, you find this sample useful. Thanks!
I’ve also uploaded the full Visual Studio solution to MSDN Code Samples.