Thursday, July 30, 2015

Get Search Analytics Reports programmatically in SharePoint 2013

How to get Search Analytics Reports programmatically in SharePoint 2013

Console application

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Analytics;


namespace SharePointConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            SPSite site = new SPSite("http://YourseverName/sites/Ptrends/");
            SPUserToken userToken = site.UserToken;

            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite site1 = new SPSite(site.ID, userToken))
                {
                    SPServiceContext context = SPServiceContext.GetContext(site1);
                    SearchServiceApplicationProxy searchProxy = context.GetDefaultProxy(typeof(SearchServiceApplicationProxy)) as SearchServiceApplicationProxy;
                    AnalyticsItemData usageData = searchProxy.GetRollupAnalyticsItemData((int)SearchReportTypeId.TopQuery, Guid.Empty, Guid.Empty, Guid.Empty);

                    int dailyHits = usageData.GetHitCountForDay(DateTime.Today);
                    int monthlyHits = usageData.GetHitCountForMonth(DateTime.Today);
                    Console.WriteLine(String.Format("Report Daily Hits={0}; Monthly Hits={1}", dailyHits, monthlyHits));

                    uint maxRows = 1000;
                    DateTime startDate = new DateTime(2015, 7, 1);
                    var searchResults = searchProxy.GetSearchReport((int)SearchReportTypeId.TopQuery, Guid.Empty, Guid.Empty, startDate.Date, true, maxRows);
                    if (searchResults.Count > 0)
                    {
                        foreach (QueryReportData rptData in searchResults)
                        {
                            int hitsCnt = rptData.Count;
                            string qry = rptData.Query;
                            Guid scope = rptData.Scope;
                            Console.WriteLine(String.Format("Report Count={0}; Query={1}; Scope={2}", hitsCnt, qry, scope.ToString()));
                        }
                    }
                }
            });

        }
    }
}

No comments:

Post a Comment

Building Secure Azure AI Foundry Agents with Managed Identity

  The credential problem nobody wants to own Every team that connects an Azure AI Foundry agent to Microsoft Graph, SharePoint, Outlook, or...