The popular documents can be viewed manually from the document libraries with the 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.
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.
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.
- Set and get the necessary context. Using the context, initiate the keyword query function.
- 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.
- The following syntax helps us in executing the query against the search server by initializing a SearchExecutor instance.
- Initialize the results and execute the request.
- 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.
- Then sort the result set on descending order based on the view count using the below logic.
- Now popularDocs array will have the result set sorted based on the view count.
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.
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.
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.