Get number of hits to a page – SharePoint(2013) Analytics

This post briefly explains how we can get the total number of hits to a page in SharePoint. In SharePoint 2013 Usage Analytics is integrated into Search Service Application (Pretty old news, a pre-historic event).
SharePoint analytics is useful in improving the Search experience by letting know the most popular items or most visited pages.
The code I’m going to explain will work fine. However, the below are the things to check before proceeding.

  1. Search service application must be attached to the web application(Central Admin -> Manage WebApplications -> Service Connections)
  2. Windows Timer service must be running

Know the role of Timer Service and SSA here

public static int GetNumberOfHitsPerPage(Guid siteGuid, SPListItem item)
{
   int totalHits = 0;
   
   // Total hits per page
   using (SPSite siteCollection = new SPSite(siteGuid))
   {
     using (SPWeb rootWeb = siteCollection.OpenWeb())
     {
        // Method 1:
        // How it works?
         SPServiceContext serviceContext = SPServiceContext.GetContext(siteCollection);
         ISearchServiceApplication searchServiceApplicationProxy = SearchServiceApplicationProxy.GetProxy(serviceContext);
         SPList pagesList = item.ParentList;
        // What is '1' stands for in the below line of Code?
         AnalyticsItemData analyticsItemData = searchServiceApplicationProxy.GetAnalyticsItemData(1, pagesList.ID, siteGuid, Convert.ToString(item.ID));
         totalHits = analyticsItemData.TotalHits;

        // Method 2:
        // How it works?
        // using UsageAnalytics Class
         UsageAnalytics analyticsData = new UsageAnalytics(siteCollection);
        // What is '1' stands for in the below line of Code?
         AnalyticsItemData analyticsItemData2 = analyticsData.GetAnalyticsItemData(1, item);
         totalHits = analyticsItemData2.TotalHits;
       }

       return totalHits;
    }
}

What is ‘1’ stands for in the below line of Code? Ans: EventTypeId

Here 1,2,3 and 4 are EventTypeIds. I believe there should have been a Enum type that represents these events instead of sending them as bare numbers.
1 – Views (number of times an item is viewed)
2 – Recommendation Displayed (number of times an item appeared in the recommendations – Popular Items/Recommended Items WebParts)
3 – Recommendation Clicked (number of times the link to an item was clicked when displayed in the recommendations)
4 – Search Queries (internal event for reporting purposes)

Method 1:

Important step in this method is getting the Service Context using SPServiceContext.GetContext(..):
We have two overloads of this method.

  1. GetContext(SPSite):
    Takes site collection object as a parameter. Then gets the Service Application ProxyGroup
    associated to the web application in which the site collection resides. Then creates the
    SPServiceContext object using the Service Application Proxy group object and id(of type GUID)
    of the Site Subscription object(spSiteObject.SiteSubscription)
    What is a Site Subscription?

  2. GetContext(HttpContext):
    Takes HttpContext object as parameter. Then gets the SPServiceContext value in one of the following ways and returns the object

    				// httpContext.Items is of IDictionary type
    				(SPServiceContext) httpContext.Items["Microsoft.SharePoint.SPServiceContext"]; // When HttpContext is not null
    				(or)
    				(SPServiceContext) SPThreadContext.Get("Microsoft.SharePoint.SPServiceContext"); // When HttpContext is null
    				

After getting the Service Context it’s pretty straight forward. Next we get the SSA proxy and from that analytics data.

Method 2:

In this method as a first step we create the object of ‘UsageAnalytics’ sealed class.
UsageAnalytics class has only one parameterized constructor that takes ‘SPSite’ object
as input parameter.
Then we get the ‘AnalyticsItemData’ object, contains the historical analytics data
for an item, from which we get the number of times the page was visited.