使用 KeywordPlanIdeaService,您可以发现与 Google 搜索广告系列相关的建议关键字,或检索现有关键字列表的历史指标。
生成创意
使用 KeywordPlanIdeaService.GenerateKeywordIdeas 为广告系列生成关键字提示。
您可以提供关键字和网址种子来生成提示。设置定位参数(例如地理位置、语言和投放网络设置),以缩小搜索范围。该服务会返回历史统计信息(例如搜索量数据),以帮助您决定是否在广告系列中使用这些关键字。对于熟悉 Google Ads 界面的用户,这类似于关键字规划工具。
您可以通过以下几种方式创建种子来生成关键字提示:
对于描述您所宣传内容的字词或短语,请使用
KeywordSeed(至少需要 1 个关键字,最多可使用 20 个关键字)。这可以是您要定位的一般业务类型(例如管道工),也可以是您提供的产品或服务(例如排水管清洁)。对于与您的业务相关的网页或整个网站的网址,请使用
UrlSeed。网址种子仅定位到特定网址。如果未找到任何匹配项,搜索范围会自动扩大到同一网域中的网页。对于网址种子,该服务不会使用超链接的内容来生成关键字提示。
对于关键字种子和网址种子,请使用
KeywordAndUrlSeed(需要 1 到 20 个关键字以及一个网址)。与只指定
UrlSeed相比,同时指定KeywordAndUrlSeed可产生更多的关键字提示。对于整个网站,请使用
SiteSeed。给定一个顶级域名(例如www.example.com),网站种子会根据公开信息生成最多 25 万个关键字提示。
如需缩小定位范围,您可以配置language、地理位置(最多 10 个 geo_target_constants)、keyword_plan_network、include_adult_keywords、keyword_annotation(优化关键字)和historical_metrics_options。
响应支持分页(每页最多 10,000 个结果;请始终检查 next_page_token 以确定是否有其他页面,因为在最后一页之前,页面返回的结果可能少于 page_size 个)。每个 GenerateKeywordIdeaResult 都会返回规范 text(带有 close_variants)、用于在生成预测指标之前进行过滤的历史 keyword_idea_metrics,以及可选的 keyword_annotations。
请求和响应字段参考
在以下端点调用 KeywordPlanIdeaService.GenerateKeywordIdeas:
POST https://googleads.googleapis.com/v26/customers/{customer_id}:generateKeywordIdeas
下表总结了 GenerateKeywordIdeasRequest 的字段和限制:
| 请求字段 | 要求 | 格式和限制 |
|---|---|---|
customer_id |
必填 | 10 位数的客户 ID (string),不带连字符。 |
seed (oneof) |
必填 | 指定以下其中一项: • keyword_seed:keywords[](1 到 20 个字符串)。• url_seed:url(特定网页网址)。• keyword_and_url_seed:url 加上 1 到 20 个 keywords[]。• site_seed:site(域名,例如 www.example.com,最多返回 250,000 个提示)。 |
language |
可选 | 语言条件资源名称(languageConstants/{criterion_id},例如 languageConstants/1000 表示英语)。请参阅语言常量。如果省略,则会包含所有语言的关键字。 |
geo_target_constants[] |
可选 | 最多 10 个地理位置资源名称(geoTargetConstants/{criterion_id},例如美国的 geoTargetConstants/2840)。请参阅地理位置定位范围。如果列表为空,则定位到所有地理位置。 |
keyword_plan_network |
可选 | KeywordPlanNetwork(GOOGLE_SEARCH 或 GOOGLE_SEARCH_AND_PARTNERS)。默认值为 GOOGLE_SEARCH_AND_PARTNERS。 |
include_adult_keywords |
可选 | bool,用于控制是否返回成人关键字。默认设置为 false。 |
keyword_annotation[] |
可选 | 用于填充每个结果上的 keyword_annotations 的 KeywordPlanKeywordAnnotation 值(例如 KEYWORD_CONCEPT)列表。 |
aggregate_metrics |
可选 | KeywordPlanAggregateMetrics,其中 aggregate_metric_types 设置为 DEVICE,用于返回 aggregate_metric_results 中按设备细分的搜索次数。 |
historical_metrics_options |
可选 | HistoricalMetricsOptions,指定可选的 year_month_range(过去 4 年内可用;默认为过去 12 个月)和 include_average_cpc。 |
page_size和page_token |
可选 | 每页结果数上限(int32,最多 10,000)和来自 next_page_token 的延续令牌。在分页请求中,所有其他请求字段应保持一致。 |
GenerateKeywordIdeaResponse 消息会返回以下字段:
| 响应字段 | 类型 | 说明 |
|---|---|---|
results[].text |
string |
表示建议及其组合 close_variants[] 的规范关键字提示文字。 |
results[].close_variants[] |
string[] |
已合并到此GenerateKeywordIdeaResult中的近似变体形式。 |
results[].keyword_idea_metrics |
KeywordPlanHistoricalMetrics |
搜索量: avg_monthly_searches(12 个月的平均值)和 monthly_search_volumes[](year、month、monthly_searches)。竞争程度: competition(LOW、MEDIUM、HIGH)和 competition_index(0 到 100)。出价和每次点击费用: low_top_of_page_bid_micros(第 20 百分位)、high_top_of_page_bid_micros(第 80 百分位)和 average_cpc_micros(在 include_average_cpc = true 时填充)。 |
results[].keyword_annotations |
KeywordAnnotations |
在 keyword_annotation 中请求 KEYWORD_CONCEPT 时填充;包含 concepts[](name、concept_group.name 和 concept_group.type)。 |
aggregate_metric_results |
KeywordPlanAggregateMetricResults |
在 aggregate_metrics 中请求 DEVICE 时填充;包含 device_searches[](MOBILE、TABLET、DESKTOP)。 |
next_page_token和total_size |
string、int64 |
下一页的延续令牌(在最后一页省略)以及可用关键字提示的总数。 |
代码示例
Java
private void runExample( GoogleAdsClient googleAdsClient, long customerId, long languageId, List<Long> locationIds, List<String> keywords, @Nullable String pageUrl) { try (KeywordPlanIdeaServiceClient keywordPlanServiceClient = googleAdsClient.getLatestVersion().createKeywordPlanIdeaServiceClient()) { GenerateKeywordIdeasRequest.Builder requestBuilder = GenerateKeywordIdeasRequest.newBuilder() .setCustomerId(Long.toString(customerId)) // Sets the language resource using the provided language ID. .setLanguage(ResourceNames.languageConstant(languageId)) // Sets the network. To restrict to only Google Search, change the parameter below to // KeywordPlanNetwork.GOOGLE_SEARCH. .setKeywordPlanNetwork(KeywordPlanNetwork.GOOGLE_SEARCH_AND_PARTNERS); // Adds the resource name of each location ID to the request. for (Long locationId : locationIds) { requestBuilder.addGeoTargetConstants(ResourceNames.geoTargetConstant(locationId)); } // Makes sure that keywords and/or page URL were specified. The request must have exactly one // of urlSeed, keywordSeed, or keywordAndUrlSeed set. if (keywords.isEmpty() && pageUrl == null) { throw new IllegalArgumentException( "At least one of keywords or page URL is required, but neither was specified."); } if (keywords.isEmpty()) { // Only page URL was specified, so use a UrlSeed. requestBuilder.getUrlSeedBuilder().setUrl(pageUrl); } else if (pageUrl == null) { // Only keywords were specified, so use a KeywordSeed. requestBuilder.getKeywordSeedBuilder().addAllKeywords(keywords); } else { // Both page URL and keywords were specified, so use a KeywordAndUrlSeed. requestBuilder.getKeywordAndUrlSeedBuilder().setUrl(pageUrl).addAllKeywords(keywords); } // Sends the keyword ideas request. GenerateKeywordIdeasPagedResponse response = keywordPlanServiceClient.generateKeywordIdeas(requestBuilder.build()); // Prints each result in the response. for (GenerateKeywordIdeaResult result : response.iterateAll()) { System.out.printf( "Keyword idea text '%s' has %d average monthly searches and '%s' competition.%n", result.getText(), result.getKeywordIdeaMetrics().getAvgMonthlySearches(), result.getKeywordIdeaMetrics().getCompetition()); } } }
C#
public void Run(GoogleAdsClient client, long customerId, long[] locationIds, long languageId, string[] keywordTexts, string pageUrl) { KeywordPlanIdeaServiceClient keywordPlanIdeaService = client.GetService(Services.V26.KeywordPlanIdeaService); // Make sure that keywords and/or page URL were specified. The request must have // exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set. if (keywordTexts.Length == 0 && string.IsNullOrEmpty(pageUrl)) { throw new ArgumentException("At least one of keywords or page URL is required, " + "but neither was specified."); } // Specify the optional arguments of the request as a keywordSeed, UrlSeed, // or KeywordAndUrlSeed. GenerateKeywordIdeasRequest request = new GenerateKeywordIdeasRequest() { CustomerId = customerId.ToString(), }; if (keywordTexts.Length == 0) { // Only page URL was specified, so use a UrlSeed. request.UrlSeed = new UrlSeed() { Url = pageUrl }; } else if (string.IsNullOrEmpty(pageUrl)) { // Only keywords were specified, so use a KeywordSeed. request.KeywordSeed = new KeywordSeed(); request.KeywordSeed.Keywords.AddRange(keywordTexts); } else { // Both page URL and keywords were specified, so use a KeywordAndUrlSeed. request.KeywordAndUrlSeed = new KeywordAndUrlSeed(); request.KeywordAndUrlSeed.Url = pageUrl; request.KeywordAndUrlSeed.Keywords.AddRange(keywordTexts); } // Create a list of geo target constants based on the resource name of specified // location IDs. foreach (long locationId in locationIds) { request.GeoTargetConstants.Add(ResourceNames.GeoTargetConstant(locationId)); } request.Language = ResourceNames.LanguageConstant(languageId); // Set the network. To restrict to only Google Search, change the parameter below to // KeywordPlanNetwork.GoogleSearch. request.KeywordPlanNetwork = KeywordPlanNetwork.GoogleSearchAndPartners; try { // Generate keyword ideas based on the specified parameters. var response = keywordPlanIdeaService.GenerateKeywordIdeas(request); // Iterate over the results and print its detail. foreach (GenerateKeywordIdeaResult result in response) { KeywordPlanHistoricalMetrics metrics = result.KeywordIdeaMetrics; Console.WriteLine($"Keyword idea text '{result.Text}' has " + $"{metrics.AvgMonthlySearches} average monthly searches and competition " + $"is {metrics.Competition}."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } }
PHP
public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId, array $locationIds, int $languageId, array $keywords, ?string $pageUrl ) { $keywordPlanIdeaServiceClient = $googleAdsClient->getKeywordPlanIdeaServiceClient(); // Make sure that keywords and/or page URL were specified. The request must have exactly one // of urlSeed, keywordSeed, or keywordAndUrlSeed set. if (empty($keywords) && is_null($pageUrl)) { throw new \InvalidArgumentException( 'At least one of keywords or page URL is required, but neither was specified.' ); } // Specify the optional arguments of the request as a keywordSeed, urlSeed, // or keywordAndUrlSeed. $requestOptionalArgs = []; if (empty($keywords)) { // Only page URL was specified, so use a UrlSeed. $requestOptionalArgs['url_seed'] = new UrlSeed(['url' => $pageUrl]); } elseif (is_null($pageUrl)) { // Only keywords were specified, so use a KeywordSeed. $requestOptionalArgs['keyword_seed'] = new KeywordSeed(['keywords' => $keywords]); } else { // Both page URL and keywords were specified, so use a KeywordAndUrlSeed. $requestOptionalArgs['keyword_and_url_seed'] = new KeywordAndUrlSeed(['url' => $pageUrl, 'keywords' => $keywords]); } // Create a list of geo target constants based on the resource name of specified location // IDs. $geoTargetConstants = array_map(function ($locationId) { return ResourceNames::forGeoTargetConstant($locationId); }, $locationIds); // Generate keyword ideas based on the specified parameters. $response = $keywordPlanIdeaServiceClient->generateKeywordIdeas( new GenerateKeywordIdeasRequest([ // Set the language resource using the provided language ID. 'language' => ResourceNames::forLanguageConstant($languageId), 'customer_id' => $customerId, // Add the resource name of each location ID to the request. 'geo_target_constants' => $geoTargetConstants, // Set the network. To restrict to only Google Search, change the parameter below to // KeywordPlanNetwork::GOOGLE_SEARCH. 'keyword_plan_network' => KeywordPlanNetwork::GOOGLE_SEARCH_AND_PARTNERS ] + $requestOptionalArgs) ); // Iterate over the results and print its detail. foreach ($response->iterateAllElements() as $result) { /** @var GenerateKeywordIdeaResult $result */ // Note that the competition printed below is enum value. // For example, a value of 2 will be returned when the competition is 'LOW'. // A mapping of enum names to values can be found at KeywordPlanCompetitionLevel.php. printf( "Keyword idea text '%s' has %d average monthly searches and competition as %d.%s", $result->getText(), is_null($result->getKeywordIdeaMetrics()) ? 0 : $result->getKeywordIdeaMetrics()->getAvgMonthlySearches(), is_null($result->getKeywordIdeaMetrics()) ? 0 : $result->getKeywordIdeaMetrics()->getCompetition(), PHP_EOL ); } }
Python
def main( client: GoogleAdsClient, customer_id: str, location_ids: list[str], language_id: str, keyword_texts: list[str], page_url: str, ): keyword_plan_idea_service: KeywordPlanIdeaServiceClient = ( client.get_service("KeywordPlanIdeaService") ) keyword_competition_level_enum: KeywordPlanCompetitionLevelEnum = ( client.enums.KeywordPlanCompetitionLevelEnum ) keyword_plan_network: KeywordPlanNetworkEnum = ( client.enums.KeywordPlanNetworkEnum.GOOGLE_SEARCH_AND_PARTNERS ) location_rns: list[str] = map_locations_ids_to_resource_names( client, location_ids ) google_ads_service: GoogleAdsServiceClient = client.get_service( "GoogleAdsService" ) language_rn: str = google_ads_service.language_constant_path(language_id) # Either keywords or a page_url are required to generate keyword ideas # so this raises an error if neither are provided. if not (keyword_texts or page_url): raise ValueError( "At least one of keywords or page URL is required, " "but neither was specified." ) # Only one of the fields "url_seed", "keyword_seed", or # "keyword_and_url_seed" can be set on the request, depending on whether # keywords, a page_url or both were passed to this function. request: GenerateKeywordIdeasRequest = client.get_type( "GenerateKeywordIdeasRequest" ) request.customer_id = customer_id request.language = language_rn request.geo_target_constants = location_rns request.include_adult_keywords = False request.keyword_plan_network = keyword_plan_network # To generate keyword ideas with only a page_url and no keywords we need # to initialize a UrlSeed object with the page_url as the "url" field. if not keyword_texts and page_url: request.url_seed.url = page_url # To generate keyword ideas with only a list of keywords and no page_url # we need to initialize a KeywordSeed object and set the "keywords" field # to be a list of StringValue objects. if keyword_texts and not page_url: request.keyword_seed.keywords.extend(keyword_texts) # To generate keyword ideas using both a list of keywords and a page_url we # need to initialize a KeywordAndUrlSeed object, setting both the "url" and # "keywords" fields. if keyword_texts and page_url: request.keyword_and_url_seed.url = page_url request.keyword_and_url_seed.keywords.extend(keyword_texts) keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas( request=request ) idea: GenerateKeywordIdeaResult for idea in keyword_ideas: competition_value = idea.keyword_idea_metrics.competition.name print( f'Keyword idea text "{idea.text}" has ' f'"{idea.keyword_idea_metrics.avg_monthly_searches}" ' f'average monthly searches and "{competition_value}" ' "competition.\n" )
Ruby
def generate_keyword_ideas(customer_id, location_ids, language_id, keywords, page_url) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new # Make sure that keywords and/or page URL were specified. The request must # have exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set. if keywords.reject {|k| k.nil?}.empty? && page_url.nil? raise "At least one of keywords or page URL is required." end kp_idea_service = client.service.keyword_plan_idea options_hash = if keywords.empty? seed = client.resource.url_seed do |seed| seed.url = page_url end {url_seed: seed} elsif page_url.nil? seed = client.resource.keyword_seed do |seed| keywords.each do |keyword| seed.keywords << keyword end end {keyword_seed: seed} else seed = client.resource.keyword_and_url_seed do |seed| seed.url = page_url keywords.each do |keyword| seed.keywords << keyword end end {keyword_and_url_seed: seed} end geo_target_constants = location_ids.map do |location_id| client.path.geo_target_constant(location_id) end include_adult_keywords = true response = kp_idea_service.generate_keyword_ideas( customer_id: customer_id, language: client.path.language_constant(language_id), geo_target_constants: geo_target_constants, include_adult_keywords: include_adult_keywords, # To restrict to only Google Search, change the parameter below to # :GOOGLE_SEARCH keyword_plan_network: :GOOGLE_SEARCH_AND_PARTNERS, **options_hash ) response.each do |result| monthly_searches = if result.keyword_idea_metrics.nil? 0 else result.keyword_idea_metrics.avg_monthly_searches end competition = if result.keyword_idea_metrics.nil? :UNSPECIFIED else result.keyword_idea_metrics.competition end puts "Keyword idea text #{result.text} has #{monthly_searches} average " + "monthly searches and competition as #{competition}." end end
Perl
sub generate_keyword_ideas { my ( $api_client, $customer_id, $location_ids, $language_id, $keyword_texts, $page_url ) = @_; # Make sure that keywords and/or page URL were specified. The request must have # exactly one of urlSeed, keywordSeed, or keywordAndUrlSeed set. if (not scalar @$keyword_texts and not $page_url) { die "At least one of keywords or page URL is required, " . "but neither was specified."; } # Specify the optional arguments of the request as a keywordSeed, urlSeed, # or keywordAndUrlSeed. my $request_option_args = {}; if (!scalar @$keyword_texts) { # Only page URL was specified, so use a UrlSeed. $request_option_args->{urlSeed} = Google::Ads::GoogleAds::V26::Services::KeywordPlanIdeaService::UrlSeed-> new({ url => $page_url }); } elsif (not $page_url) { # Only keywords were specified, so use a KeywordSeed. $request_option_args->{keywordSeed} = Google::Ads::GoogleAds::V26::Services::KeywordPlanIdeaService::KeywordSeed ->new({ keywords => $keyword_texts }); } else { # Both page URL and keywords were specified, so use a KeywordAndUrlSeed. $request_option_args->{keywordAndUrlSeed} = Google::Ads::GoogleAds::V26::Services::KeywordPlanIdeaService::KeywordAndUrlSeed ->new({ url => $page_url, keywords => $keyword_texts }); } # Create a list of geo target constants based on the resource name of specified # location IDs. my $geo_target_constants = [ map ( Google::Ads::GoogleAds::V26::Utils::ResourceNames::geo_target_constant( $_), @$location_ids)]; # Generate keyword ideas based on the specified parameters. my $keyword_ideas_response = $api_client->KeywordPlanIdeaService()->generate_keyword_ideas({ customerId => $customer_id, # Set the language resource using the provided language ID. language => Google::Ads::GoogleAds::V26::Utils::ResourceNames::language_constant( $language_id), # Add the resource name of each location ID to the request. geoTargetConstants => $geo_target_constants, # Set the network. To restrict to only Google Search, change the parameter below # to GOOGLE_SEARCH. keywordPlanNetwork => GOOGLE_SEARCH_AND_PARTNERS, %$request_option_args }); # Iterate over the results and print its detail. foreach my $result (@{$keyword_ideas_response->{results}}) { printf "Keyword idea text '%s' has %d average monthly searches " . "and '%s' competition.\n", $result->{text}, $result->{keywordIdeaMetrics}{avgMonthlySearches} ? $result->{keywordIdeaMetrics}{avgMonthlySearches} : 0, $result->{keywordIdeaMetrics}{competition} ? $result->{keywordIdeaMetrics}{competition} : "undef"; } return 1; }
curl
# This code example generates keyword ideas. # # Variables: # API_VERSION, # CUSTOMER_ID, # MANAGER_CUSTOMER_ID, # OAUTH2_ACCESS_TOKEN: # See https://developers.google.com/google-ads/api/rest/auth#request_headers # for details. # # LANGUAGE: The resource name of the language to target. This is in the format # of "languageConstants/{criterion_id}". See # https://developers.google.com/google-ads/api/data/codes-formats#languages # for the available criterion_id values. # GEO_TARGET_CONSTANT: The resource name of the geo target constant to # generate keyword ideas for. This is in the format of # "geoTargetConstants/{criterion_id}". See # https://developers.google.com/google-ads/api/data/geotargets for the # available criterion_id values. # KEYWORD: The keyword to generate keyword ideas for. # URL: The URL of the website to generate keyword ideas for. curl -f --request POST \ "https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}:generateKeywordIdeas" \ --header "Content-Type: application/json" \ --header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \ --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ --data @- <<EOF { "language": "${LANGUAGE}", "geoTargetConstants": [ "${GEO_TARGET_CONSTANT}" ], "includeAdultKeywords": false, "keywordPlanNetwork": "GOOGLE_SEARCH", "keywordAndUrlSeed": { "keywords": [ "${KEYWORD}" ], "url": "${URL}" } } EOF
REST 请求和响应结构
以下示例使用 keywordAndUrlSeed、英语 (languageConstants/1000) 和美国 (geoTargetConstants/2840) 向 KeywordPlanIdeaService.GenerateKeywordIdeas 发送 POST 请求:
POST https://googleads.googleapis.com/v26/customers/{customer_id}:generateKeywordIdeas
{
"language": "languageConstants/1000",
"geoTargetConstants": [
"geoTargetConstants/2840"
],
"includeAdultKeywords": false,
"keywordPlanNetwork": "GOOGLE_SEARCH",
"keywordAnnotation": [
"KEYWORD_CONCEPT"
],
"keywordAndUrlSeed": {
"url": "https://www.example.com/mars-cruises",
"keywords": [
"mars cruise",
"space vacation"
]
}
}
成功的响应会返回 results[] 中的 GenerateKeywordIdeaResult 行,以及历史搜索量和出价范围:
{
"results": [
{
"text": "mars cruise",
"keywordIdeaMetrics": {
"avgMonthlySearches": "12100",
"competition": "MEDIUM",
"competitionIndex": "54",
"lowTopOfPageBidMicros": "1450000",
"highTopOfPageBidMicros": "4800000",
"monthlySearchVolumes": [
{
"year": "2026",
"month": "MAY",
"monthlySearches": "14800"
}
]
},
"keywordAnnotations": {
"concepts": [
{
"name": "Space Travel",
"conceptGroup": {
"name": "Travel",
"type": "OTHERS"
}
}
]
}
}
],
"totalSize": "1"
}
映射到界面
下表将 KeywordPlanIdeaService.GenerateKeywordIdeas 参数映射到 Google Ads 界面中的关键字规划工具: