Programatically getting most popular documents in SharePoint 2019 On Premise

Mayank Bhargava 21 Reputation points

Please advise or share sample code on how to get the most viewed items in SharePoint 2019 programmatically, I am open to using SharePoint rest API, SPFx, Server side object model
Also, advise if possible we can get that directly from the database.

SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,708 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,577 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 32,156 Reputation points Microsoft Vendor

    Hi @Mayank Bhargava
    You could use pnp search to search in Shared Documents library. For most Viewed Documents we get all the results and sort them by “ViewsLifeTime”.
    Below is my sample code for your reference:

     import { sp , SortDirection,ISearchQuery, SearchResults, SearchQueryBuilder} from "@pnp/sp/presets/all";  
        let query=`Path: AND ContentClass:STS_ListItem` ;      
        const results2: SearchResults = await<ISearchQuery>{  
         Querytext: query,  
         RowLimit: 10,  
         EnableInterleaving: true,  
           Property: 'ViewsLifeTime',  
           Direction: SortDirection.Descending  
       console.log(results2.PrimarySearchResults[0]); //most viewed documents  


    Note: Microsoft is providing this information as a convenience to you. The sites are not controlled by Microsoft. Microsoft cannot make any representations regarding the quality, safety, or suitability of any software or information found there. Please make sure that you completely understand the risk before retrieving any suggestions from the above link.

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.