簡體   English   中英

如何使用谷歌 api ruby gem 查詢谷歌分析 api?

[英]How to query google analytics api using the google api ruby gem?

google api ruby 客戶端的文檔缺乏實際示例,僅記錄了類和方法,因此很難猜測我們應該如何在現實生活中使用 gem。 例如,我試圖從enhanced ecommerce中獲取所有購買,以查看它們來自哪里(獲取渠道或渠道分組),但我只對需要 5 個會話才能轉換交易的交易感興趣(我們unconvinced clients )。

首先你需要你的analytics view_id,可以在末尾的url中獲得,在字母p之后

在此處輸入圖像描述

然后您需要將路由導出到憑證: 在您的終端中:

export GOOGLE_APPLICATION_CREDENTIALS = 'folder/yourproject-a91723dsa8974.json'

有關憑據的更多信息,請參閱google-auth-gem 文檔

設置好之后就可以像這樣查詢api

require 'googleauth'
require 'google/apis/analyticsreporting_v4'

scopes = ['https://www.googleapis.com/auth/analytics']
date_from = 10.days.ago
date_to = 2.days.ago
authorization = Google::Auth.get_application_default(scopes)
analytics = Google::Apis::AnalyticsreportingV4::AnalyticsReportingService.new
analytics.authorization = authorization
view_id = '189761131'
date_range = Google::Apis::AnalyticsreportingV4::DateRange.new(start_date: date_from.strftime('%Y-%m-%d'), end_date: date_to.strftime('%Y-%m-%d'))
metric = Google::Apis::AnalyticsreportingV4::Metric.new(expression: 'ga:transactions')
transaction_id_dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:transactionID')
adquisition_dimension = Google::Apis::AnalyticsreportingV4::Dimension.new(name: 'ga:channelGrouping')
filters = 'ga:sessionsToTransaction==5'

request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
  report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
    view_id: view_id,
    metrics: [metric],
    dimensions: [transaction_id_dimension, adquisition_dimension],
    date_ranges: [date_range],
    filters_expression: filters
  )]
)
response = analytics.batch_get_reports(request)
response.reports.first.data.rows.each do |row|
  dimensions = row.dimensions
  puts "TransactionID: #{dimensions[0]} - Channel: #{dimensions[1]}"
end

注意filters_expression: filters

其中過濾器變量的形式為ga:medium==cpc,ga:medium==organic;ga:source==bing,ga:source==google

其中逗號 ( , ) 表示OR並且分號 ( ; ) 表示AND (其中OR優先於AND

您可以檢查查詢資源管理器以使用過濾器。

這是過濾器文檔

如果報告帶來超過 1000 行(默認最大行),則會出現 next_page_token 屬性。

response.reports.first.next_page_token
=> "1000"

您必須存儲該號碼才能在下一個 ReportRequest 中使用它

next_request = Google::Apis::AnalyticsreportingV4::GetReportsRequest.new(
  report_requests: [Google::Apis::AnalyticsreportingV4::ReportRequest.new(
    view_id: view_id,
    metrics: [metric],
    dimensions: [transaction_id_dimension, adquisition_dimension],
    date_ranges: [date_range],
    filters_expression: filters,
    page_token: "1000"
  )]
)

直到

next_response.reports.first.next_page_toke
=> nil

或者,您可以通過添加page_size: 10_000來更改報告請求的默認頁面大小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM