Retrieve Popular Documents Programmatically In SharePoint using JSOM and REST API

Introduction

The popular documents can be viewed manually from the document libraries withthe popular items tab. In this article, you will learn how to fetch popular documents based on view counts using JSOM and REST API. This will be applicable for all SharePoint platforms.

Prerequisite

You have to enable the reporting feature under site collection features in the site to see the popular documents. This data can be retrieved using search queries. Basically this is part of SharePoint analytics. 

Using JSOM

The Keyword query language in SharePoint helps us getting the popularity results for the items present on the document libraries. The following steps show you detailed view. 
  1. Set and get the necessary context. Using the context, initiate the keyword query function.
    1. var searchContext = new SP.ClientContext();  
    2. var searchQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(searchContext);  
  2. The results can be retrieved using multiple query filters. In this case, I am using path variable to filter the data. This helps us in getting results for one particular library. Multiple document library data can also be viewed by setting the filters with 'and' parameter. Set the query text as below.
    1. searchQuery.set_queryText("path:http://siteurl/Documents”)  
  3. The following syntax helps us in executing the query against the search server by initializing a SearchExecutor instance.
    1. var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(searchContext);  
  4. Initialize the results and execute the request.
    1. searchRes = searchExecutor.executeQuery(searchQuery);  
    2. searchContext.executeQueryAsync(SearchResults, QueryFailed);  
  5. In the success function, expand the result set (searchRes) to see the document results. The following code snippet shows you to parse the search results.
    1. var resultSet = searchRes.m_value.ResultTables[0].ResultRows;  
    2. var popularDocs = new Array();  
    3. for(var i = 0; i < resultSet.length; i++)  
    4. {  
    5.     popularDocs[i] = [resultSet[i].Title,resultSet[i].ViewsLifeTime];  
    6. }  
  6. Then sort the result set on descending order based on the view count using the below logic.
    1. function Sort(a, b) {  
    2.     return (a[1] > b[1] ? -1 : (a[1] < b[1] ? 1 : 0));  
    3. }  
  7. Now popularDocs array will have the result set sorted based on the view count.
    1. popularDocs.sort(Sort);  
Using REST API

The Search REST API can also be used to fetch the view counts for the documents. Again we will use path parameter to filter the results for one particular document library.

We will build the rest query first. In the query URL, you can set the necessary filters required. The advantage of using REST is sorting can be done by setting sortlist parameter. Please find the below query URL.

This will fetch all the document related items and we will filter out the necessary values using the code logic. JQuery Ajax call is used to fetch the results.

The below code snippet shows the implementation.

  1. $.ajax({   
  2.     url: "/_api/search/query?querytext='path:http://siteurl/Documents'&sortlist='ViewsLifeTime:descending'",   
  3.     method: "GET",   
  4.     headers: {"accept""application/json;odata=verbose",   
  5.     },   
  6.     success: function(data){  
  7.         var restResults = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;  
  8.         var popularRestResults = new Array();  
  9.         for(var i=0;i<restResults.length;i++){  
  10.             popularRestResults[i] = [restResults[i].Cells.results[3]["Value"],restResults[i].Cells.results[20]["Value"]];  
  11.         }  
  12.     },   
  13.     error: function(sender,args){  
  14.     }   
  15. });  
The popularRestResults[0] or restResults[0] will be the most popular document item. The below image shows the necessary results. restResults[i].Cells.results[3]["Value"] gives the title and restResults[i].Cells.results[20]["Value"] gives the views count for the corresponding item.

 
Note: The filtering of the result set can be done based on the filter parameters. In this article, you have seen how data can be filtered with very limited set of filtering options. Other filtering like row limits, refiners or select parameters can be used to filter the results further.
 
Summary

Thus you have learnt how the view counts for documents under document libraries can be retrieved. With that, you have seen how the most popular documents can be identified. 
 
Read more articles on SharePoint:

Up Next
    Ebook Download
    View all
    Learn
    View all