Skip to content

Commit 0decc98

Browse files
committed
Add GenerateHistoricalMetrics example
Change-Id: Ib75850f2a3edf94d6e1ad4df7583919d6fc223b8
1 parent bec9265 commit 0decc98

1 file changed

Lines changed: 157 additions & 0 deletions

File tree

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
// Copyright 2019 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package com.google.ads.googleads.examples.planning;
16+
17+
import com.beust.jcommander.Parameter;
18+
import com.google.ads.googleads.examples.utils.ArgumentNames;
19+
import com.google.ads.googleads.examples.utils.CodeSampleParams;
20+
import com.google.ads.googleads.lib.GoogleAdsClient;
21+
import com.google.ads.googleads.v11.common.MonthlySearchVolume;
22+
import com.google.ads.googleads.v11.errors.GoogleAdsError;
23+
import com.google.ads.googleads.v11.errors.GoogleAdsException;
24+
import com.google.ads.googleads.v11.services.GenerateHistoricalMetricsResponse;
25+
import com.google.ads.googleads.v11.services.KeywordPlanKeywordHistoricalMetrics;
26+
import com.google.ads.googleads.v11.services.KeywordPlanServiceClient;
27+
import com.google.ads.googleads.v11.utils.ResourceNames;
28+
import com.google.protobuf.ProtocolStringList;
29+
import java.io.FileNotFoundException;
30+
import java.io.IOException;
31+
32+
/**
33+
* Generates historical metrics for a keyword plan. To create a keyword plan, run the {@link
34+
* AddKeywordPlan} example.
35+
*/
36+
public class GenerateHistoricalMetrics {
37+
38+
private static class GenerateHistoricalMetricsParams extends CodeSampleParams {
39+
40+
@Parameter(
41+
names = ArgumentNames.CUSTOMER_ID,
42+
description = "The customer in which to create a new keyword plan.")
43+
public Long customerId;
44+
45+
@Parameter(
46+
names = ArgumentNames.KEYWORD_PLAN_ID,
47+
description = "The keyword plan ID for which to generate metrics.")
48+
public Long keywordPlanId;
49+
}
50+
51+
public static void main(String[] args) {
52+
GenerateHistoricalMetricsParams params = new GenerateHistoricalMetricsParams();
53+
if (!params.parseArguments(args)) {
54+
55+
// Optional, specify the customer ID for which the call is made.
56+
params.customerId = Long.valueOf("INSERT_CUSTOMER_ID");
57+
58+
params.keywordPlanId = Long.valueOf("INSERT_KEYWORD_PLAN_ID");
59+
}
60+
GoogleAdsClient googleAdsClient = null;
61+
try {
62+
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
63+
} catch (FileNotFoundException fnfe) {
64+
System.err.printf(
65+
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
66+
System.exit(1);
67+
} catch (IOException ioe) {
68+
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
69+
System.exit(1);
70+
}
71+
72+
try {
73+
new GenerateHistoricalMetrics()
74+
.runExample(googleAdsClient, params.customerId, params.keywordPlanId);
75+
} catch (GoogleAdsException gae) {
76+
// GoogleAdsException is the base class for most exceptions thrown by an API request.
77+
// Instances of this exception have a message and a GoogleAdsFailure that contains a
78+
// collection of GoogleAdsErrors that indicate the underlying causes of the
79+
// GoogleAdsException.
80+
System.err.printf(
81+
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
82+
gae.getRequestId());
83+
int i = 0;
84+
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
85+
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
86+
}
87+
System.exit(1);
88+
}
89+
}
90+
91+
/**
92+
* Runs the code example.
93+
*
94+
* @param googleAdsClient the Google Ads API client.
95+
* @param customerId the client customer ID.
96+
* @param planId the plan ID.
97+
*/
98+
// [START generate_historical_metrics]
99+
private void runExample(GoogleAdsClient googleAdsClient, Long customerId, Long planId) {
100+
String resourceName = ResourceNames.keywordPlan(customerId, planId);
101+
102+
try (KeywordPlanServiceClient keywordPlanServiceClient =
103+
googleAdsClient.getLatestVersion().createKeywordPlanServiceClient()) {
104+
GenerateHistoricalMetricsResponse response =
105+
keywordPlanServiceClient.generateHistoricalMetrics(resourceName);
106+
107+
for (KeywordPlanKeywordHistoricalMetrics metric : response.getMetricsList()) {
108+
// These metrics include those for both the search query and any close variants included in
109+
// the response.
110+
111+
ProtocolStringList variants = metric.getCloseVariantsList();
112+
String variantsList =
113+
(variants.isEmpty())
114+
? ""
115+
: String.format(" (and the following variants: %s)", String.join(", ", variants));
116+
117+
System.out.printf(
118+
"The search query '%s'%s generated the following historical metrics:%n",
119+
metric.getSearchQuery(), variantsList);
120+
121+
// Approximate number of monthly searches on this query averaged for the past 12 months.
122+
System.out.printf(
123+
"\tApproximate monthly searches: %d.%n",
124+
metric.getKeywordMetrics().getAvgMonthlySearches());
125+
126+
// The competition level for this search query.
127+
System.out.printf(
128+
"\tCompetition level: %s.%n", metric.getKeywordMetrics().getCompetition().name());
129+
130+
// The competition index for the query in the range [0, 100]. This shows how competitive ad
131+
// placement is for a keyword. The level of competition from 0-100 is determined by the
132+
// number of ad slots filled divided by the total number of ad slots available. If not
133+
// enough data is available, None will be returned.
134+
System.out.printf(
135+
"\tCompetition index: %d.%n", metric.getKeywordMetrics().getCompetitionIndex());
136+
137+
// Top of page bid low range (20th percentile) in micros for the keyword.
138+
System.out.printf(
139+
"\tTop of page bid low range %d.%n",
140+
metric.getKeywordMetrics().getLowTopOfPageBidMicros());
141+
142+
// Top of page bid high range (80th percentile) in micros for the keyword.
143+
System.out.printf(
144+
"\tTop of page bid high range %d.%n",
145+
metric.getKeywordMetrics().getHighTopOfPageBidMicros());
146+
147+
// Approximate number of searches on this query for the past twelve months.
148+
for (MonthlySearchVolume month : metric.getKeywordMetrics().getMonthlySearchVolumesList()) {
149+
System.out.printf(
150+
"\tApproximately %d searches in %s, %d.%n",
151+
month.getMonthlySearches(), month.getMonth().name(), month.getYear());
152+
}
153+
}
154+
}
155+
}
156+
// [END generate_historical_metrics]
157+
}

0 commit comments

Comments
 (0)