Last active
March 2, 2024 13:00
-
-
Save unavailabl3/2ddba3d317760ef0fadce2b3931f4ff1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ gem install google-analytics-data | |
----------------------------------- | |
require 'google/analytics/data' | |
# METHOD FOR EXTRACTING VIEWS FROM REPORT | |
def extract_page_views(report) | |
report.rows.each_with_object({}) do |row, memo| | |
page_path = row.dimension_values.first.value | |
memo[page_path] = row.metric_values.first.value.to_i | |
end | |
end | |
# INITIALIZING CLIENT | |
client = Google::Analytics::Data.analytics_data do |config| | |
# try to keep the path in secrets or environment variable | |
config.credentials = '/path/to/credentials.json' | |
end | |
# PROPERTIES PREPARATION | |
BEGINS_WITH_MATCH_TYPE = Google::Analytics::Data::V1beta::Filter::StringFilter::MatchType::BEGINS_WITH | |
property_id = 'your-ga4-property-id' | |
page_path = '/articles/' # all pages which path begins with /articles/ | |
report_start_date = '2024-03-07' | |
report_end_date = '2024-03-14' | |
report_metrics = [{ name: 'screenPageViews'}] | |
dimension_filter = { | |
filter: { | |
field_name: 'pagePath', | |
string_filter: { | |
match_type: BEGINS_WITH_MATCH_TYPE, | |
value: page_path, | |
case_sensitive: false | |
} | |
} | |
} | |
# ACTUAL REQUEST | |
request = Google::Analytics::Data::V1beta::RunReportRequest.new( | |
property: "properties/#{property_id}", | |
dimensions: [{ name: 'pagePath' }], | |
dimension_filter: dimension_filter, | |
metrics: report_metrics, | |
date_ranges: [{ start_date: report_start_date, end_date: report_end_date }] | |
) | |
report = client.run_report(request) | |
extract_page_views(report) | |
# => { | |
# '/articles/first-article' => 135, | |
# '/articles/second-article' => 20, | |
# ... | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment