Skip to main content

Cloud

SharePoint 2013 Search: JavaScript CSOM Primer

A lot of JavaScript incoming!
With the rise of SharePoint Online, custom search solutions through JavaScript have become a staple for the development work for clients. While a lot of your search basics can be handled through simple modification of Display Templates (see some of my previous blogs for some basics there), the opportunity still arises when you need to do something truly custom with your search code.
A lot of the basics are already out there for querying the Client Side Object Model through JavaScript (see this MSDN post by Cory Roth). We will review those, and take it a little deeper in order to give you a little more control over your queries and results returned.
We will cover:

  • The essentials and basics
  • Retrieving custom retrievable Managed Properties
  • Sorting by Managed Properties
  • Increase the Row Limit (results returned)
  • Setting a specific Result Source
  • Set Trim Duplicates to False

The Basics

The great part about all of the new 2013 Client Side tools is that you can just open up a Script Editor or a Content Editor Web Part and get started instantly. No need to deploy any managed code. If there’s items in your SharePoint search index and you have permission to access them, you can jump right in and get started.
Throw a div on the page with the ID “resultsDiv”, and see your table appear when you execute the JavaScript code. If you want to go deeper, simply add a button and a textbox to your page as well and replace the appropriate portions of the code.
To change the search query, just change the following line:

keywordQuery.set_queryText("New Query Text Here");
   1:  var context = SP.ClientContext.get_current();
   2:  var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
   3:  keywordQuery.set_queryText("Search Query");
   4:  var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
   5:  var results = searchExecutor.executeQuery(keywordQuery);
   6:  context.executeQueryAsync(onQuerySuccess, onQueryFail);
   7:   
   8:  function onQuerySuccess() {
   9:       $("#resultsDiv").append('<table>');
  10:       if (results.m_value.ResultTables) {
  11:          $.each(results.m_value.ResultTables, function(index, table) {
  12:              if(table.TableType == "RelevantResults") {
  13:                  $.each(results.m_value.ResultTables[index].ResultRows, function () {
  14:                        $("#resultsDiv").append('<tr>');
  15:                        $("#resultsDiv").append('<td>' + this.Title + '</td>');
  16:                        $("#resultsDiv").append('<td>' + this.Author + '</td>');
  17:                        $("#resultsDiv").append('<td>' + this.Write + '</td>');
  18:                        $("#resultsDiv").append('<td>' + this.Path + '</td>');
  19:                        $("#resultsDiv").append('</tr>');
  20:                     })
  21:                  }
  22:              });
  23:          }
  24:          $("#resultsDiv").append('</table>');
  25:  }
  26:  
  27:  function onQueryFail(){
  28:      alert('Query failed. Error:' + args.get_message());
  29:  }

Retrieving Custom Managed Properties

In the request to the search index, there is a default set of managed properties that are returned by the index. In order to return other managed properties, we must request them.

   1:  var context = SP.ClientContext.get_current();
   2:  var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
   3:  keywordQuery.set_queryText("Search Query");
   4:  
   5:  // Set Properties
   6:  var properties = keywordQuery.get_selectProperties();
   7:  properties.add('Size');
   8:  properties.add('CustomManagedProperty');
   9:   
  10:  var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
  11:  var results = searchExecutor.executeQuery(keywordQuery);
  12:  context.executeQueryAsync(onQuerySuccess, onQueryFail);
  13:   
  14:  function onQuerySuccess() {
  15:       $("#resultsDiv").append('<table>');
  16:       if (results.m_value.ResultTables) {
  17:          $.each(results.m_value.ResultTables, function(index, table) {
  18:              if(table.TableType == "RelevantResults") {
  19:                  $.each(results.m_value.ResultTables[index].ResultRows, function () {
  20:                        $("#resultsDiv").append('<tr>');
  21:                        $("#resultsDiv").append('<td>' + this.Title + '</td>');
  22:                        $("#resultsDiv").append('<td>' + this.Author + '</td>');
  23:                        $("#resultsDiv").append('<td>' + this.Write + '</td>');
  24:                        $("#resultsDiv").append('<td>' + this.Path + '</td>');
  25:   
  26:                        // Get Data from custom returned properties
  27:                        $("#resultsDiv").append('<td>' + this.Size + '</td>');
  28:                        $("#resultsDiv").append('<td>' + this.CustomManagedProperty + '</td>');
  29:   
  30:                        $("#resultsDiv").append('</tr>');
  31:                     })
  32:                  }
  33:              });
  34:          }
  35:          $("#resultsDiv").append('</table>');
  36:  }

Sorting by Managed Property

Sorting is fairly straightforward. Choose the Managed Property that you would like to sort by (make sure it’s set as Sortable!). Choose whether it needs to be Ascending or Descending. Ascending is 0, Descending is 1.

   1:  var context = SP.ClientContext.get_current();
   2:  var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
   3:  keywordQuery.set_queryText("Search Query");
   4:  
   5:  // Sorting (Ascending = 0, Descending = 1)
   6:  keywordQuery.set_enableSorting(true);
   7:  var sortproperties = keywordQuery.get_sortList();
   8:  sortproperties.add("Write", 0);
   9:   
  10:  var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
  11:  var results = searchExecutor.executeQuery(keywordQuery);
  12:  context.executeQueryAsync(onQuerySuccess, onQueryFail);

Increase the Number of Results Returned

The default number of results returned is 50 and is capped at 500. You can increase the cap through PowerShell.

   1:  var context = SP.ClientContext.get_current();
   2:  var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
   3:  keywordQuery.set_queryText("Search Query");
   4:  
   5:  // Set Row Limit
   6:  keywordQuery.set_rowLimit(500);
   7:   
   8:  var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
   9:  var results = searchExecutor.executeQuery(keywordQuery);
  10:  context.executeQueryAsync(onQuerySuccess, onQueryFail);

Setting A Specific Result Source

You will need the GUID of the Result Source.

   1:  var context = SP.ClientContext.get_current();
   2:  var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
   3:  keywordQuery.set_queryText("Search Query");
   4:  
   5:  // Set Source ID (GUID)
   6:  keywordQuery.set_sourceId("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX");
   7:   
   8:  
   9:  var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
  10:  var results = searchExecutor.executeQuery(keywordQuery);
  11:  context.executeQueryAsync(onQuerySuccess, onQueryFail);

Trim Duplicates

In the potential rare instance that you will need to see duplicates, you can set Trim Duplicates to false.

   1:  var context = SP.ClientContext.get_current();
   2:  var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(context);
   3:  keywordQuery.set_queryText("Search Query");
   4:  
   5:  // Set Trim Duplicates to False
   6:  keywordQuery.set_trimDuplicates(false);
   7:   
   8:  var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(context);
   9:  var results = searchExecutor.executeQuery(keywordQuery);
  10:  context.executeQueryAsync(onQuerySuccess, onQueryFail);

Thoughts on “SharePoint 2013 Search: JavaScript CSOM Primer”

  1. Pingback: SharePoint, Office365 & Yammer Nuggets of week 3 - Ragnar Heil: SharePoint Nuggets - Site Home - MSDN Blogs

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Follow Us
TwitterLinkedinFacebookYoutubeInstagram