Google Reporting API V4缺少值

时间:2018-10-15 15:35:36

标签: c# .net-core google-analytics-api google-reporting-api

我一直在使用Google的分析报告api v4遇到问题。当我发出请求时,我可以取回数据,但是某些维度和指标值丢失和/或不一致。

例如,如果我想要fullRefferer,它将返回(未设置)。或者当我确实获取值时,我的页面浏览量值可能是1312,而我的会话数可能是26。

我发出请求的代码如下:

public GetReportsResponse Get(string viewId, DateTime startDate, DateTime endDate, string nextPageToken = null)
    {
        try
        {
            var credential = GetCredential();
            using (var svc = new AnalyticsReportingService(
                new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential
                }))
            {
                var mets = new List<Metric>
                {
                    new Metric
                    {
                        Alias = "Users",
                        Expression = "ga:users"
                    },
                    new Metric
                    {
                        Alias = "Bounce Rate",
                        Expression = "ga:bounceRate"
                    },
                    new Metric
                    {
                        Alias = "Page Views",
                        Expression = "ga:pageViews"
                    },
                    new Metric()
                    {
                        Alias = "Sessions",
                        Expression = "ga:sessions"
                    }
                };

                var dims = new List<Dimension>
                {
                    new Dimension { Name = "ga:date" },
                    new Dimension { Name = "ga:hour" },
                    new Dimension { Name = "ga:browser" },
                    new Dimension { Name = "ga:pagePath" },
                    new Dimension { Name = "ga:fullReferrer"}
                };

                var dateRange = new DateRange
                {
                    StartDate = startDate.ToFormattedString(),
                    EndDate = endDate.ToFormattedString()
                };

                var reportRequest = new ReportRequest
                {
                    DateRanges = new List<DateRange> { dateRange },
                    Dimensions = dims,
                    Metrics = mets,
                    ViewId = viewId,
                    PageToken = nextPageToken
                };
                var getReportsRequest = new GetReportsRequest
                {
                    ReportRequests = new List<ReportRequest> { reportRequest },
                };
                var batchRequest = svc.Reports.BatchGet(getReportsRequest);
                var response = batchRequest.Execute();

                return response;
            }
        }
        catch (Exception e)
        {
            return null;
        }
    }

我用于过滤结果的代码在这里:

public static List<AnalyticEntry> Filter(Google.Apis.AnalyticsReporting.v4.Data.GetReportsResponse response)
    {
        if (response == null) return new List<AnalyticEntry>();

        List<GoogleDataDto> gData = new List<GoogleDataDto>();
        foreach (var report in response.Reports)
        {
            foreach (var row in report.Data.Rows)
            {
                GoogleDataDto dto = new GoogleDataDto();

                foreach (var metric in row.Metrics)
                {
                    foreach (var value in metric.Values)
                    {
                        int index = metric.Values.IndexOf(value);
                        var metricHeader = report.ColumnHeader.MetricHeader.MetricHeaderEntries[index];

                        switch (metricHeader.Name)
                        {
                            case "Sessions":
                                dto.Sessions = Convert.ToInt32(value);
                                break;
                            case "Bounce Rate":
                                dto.BounceRate = Convert.ToDecimal(value);
                                break;
                            case "Page Views":
                                dto.PageViews = Convert.ToInt32(value);
                                break;
                            case "Users":
                                dto.Users = Convert.ToInt32(value);
                                break;
                        }
                    }
                }

                foreach (var dimension in row.Dimensions)
                {
                    int index = row.Dimensions.IndexOf(dimension);
                    var dimensionName = report.ColumnHeader.Dimensions[index];
                    switch (dimensionName)
                    {
                        case "ga:date":
                            dto.Date = dimension;
                            break;
                        case "ga:hour":
                            dto.Hour = dimension;
                            break;
                        case "ga:browser":
                            dto.Browser = dimension;
                            break;
                        case "ga:pagePath":
                            dto.PagePath = dimension;
                            break;
                        case "ga:source":
                            dto.Source = dimension;
                            break;
                        case "ga:fullRefferer":
                            dto.Referrer = dimension;
                            break;
                    }
                }

                gData.Add(dto);
            }
        }

        return Combine(gData);
    }

    private static List<AnalyticEntry> Combine(IReadOnlyCollection<GoogleDataDto> gData)
    {
        List<AnalyticEntry> outputDtos = new List<AnalyticEntry>();

        var dates = gData.GroupBy(d => d.Date.Substring(0,6)).Select(d => d.First()).Select(d => d.Date.Substring(0,6)).ToList();

        foreach (var date in dates)
        {
            var entities = gData.Where(d => d.Date.Contains(date)).ToList();

            AnalyticEntry dto = new AnalyticEntry
            {
                Date = date.ToDate(),
                PageViews = 0,
                Sessions = 0,
                Users = 0,
                BounceRate = 0
            };


            foreach (var entity in entities)
            {
                dto.BounceRate += entity.BounceRate;
                dto.PageViews += entity.PageViews;
                dto.Users += entity.Users;
                dto.Sessions += entity.Sessions;
            }

            dto.BounceRate = dto.BounceRate / entities.Count();

            var dictionaries = entities.GetDictionaries();

            var commonBrowsers = dictionaries[0].GetMostCommon();
            var commonTimes = dictionaries[1].GetMostCommon();
            var commonPages = dictionaries[2].GetMostCommon();
            var commonSources = dictionaries[3].GetMostCommon();
            var commonReferrers = dictionaries[4].GetMostCommon();

            dto.CommonBrowser = commonBrowsers.Key;
            dto.CommonBrowserViews = commonBrowsers.Value;
            dto.CommonTimeOfDay = commonTimes.Key.ToInt();
            dto.CommonTimeOfDayViews = commonTimes.Value;
            dto.CommonPage = commonPages.Key;
            dto.CommonPageViews = commonPages.Value;
            dto.CommonSource = commonSources.Key;
            dto.CommonSourceViews = commonSources.Value;
            dto.CommonReferrer = commonReferrers.Key;
            dto.CommonReferrerViews = commonReferrers.Value;

            outputDtos.Add(dto);
        }

        return outputDtos;
    }

我不确定还有什么,请发表评论以获取更多信息:)

1 个答案:

答案 0 :(得分:0)

解决了!

最初,我试图根据数组中值的位置查找“度量标准名称”。因此,使用位置可以获取名称并设置值。

问题在于数组可能具有多个相同的值。

例如:

var arr = [1,0,3,1,1];

如果值是1,我试图使用数组中1的位置来获取名称。 因此,如果数组中1的索引为0,我将通过使用该索引并在另一个数组中找到该名称来找到它的名称。

例如:

var names = ['a','b','c'];
var values = [1,2,1];

var value = 1;
var index = values.indexOf(value); // which would be 0  

SetProperty(
    propertyName:names[index], // being a
    value: value);

尽管很难解释,但由于数组中有多个值等于同一事物,所以我多次设置了相同的值。

这是答案。经过测试并有效

public List<GoogleDataDto> Filter(GetReportsResponse response)
    {
        if (response == null) return null;

        List<GoogleDataDto> gData = new List<GoogleDataDto>();
        foreach (var report in response.Reports)
        {
            foreach (var row in report.Data.Rows)
            {
                GoogleDataDto dto = new GoogleDataDto();

                foreach (var metric in row.Metrics)
                {
                    int index = 0; // Index counter, used to get the metric name
                    foreach (var value in metric.Values)
                    {
                        var metricHeader = report.ColumnHeader.MetricHeader.MetricHeaderEntries[index];

                        //Sets property value based on the metric name
                        dto.SetMetricValue(metricHeader.Name, value);
                        index++;
                    }
                }

                int dIndex = 0; // Used to get dimension name
                foreach (var dimension in row.Dimensions)
                {
                    var dimensionName = report.ColumnHeader.Dimensions[dIndex];

                    //Sets property value based on dimension name
                    dto.SetDimensionValue(dimensionName, dimension);

                    dIndex++;
                }

                // Will only add the dto to the list if its not a duplicate
                if (!gData.IsDuplicate(dto))
                    gData.Add(dto);
            }
        }

        return gData;
    }