您可以通过两种方法使用 Search Ads 360 Reporting API 检索实体和报告数据。
本指南主要介绍如何处理来自 SearchAds360Service
的数据流。以下是这两种数据检索方法之间的概要区别:
SearchAds360Service.SearchStream | SearchAds360Service.Search | |
---|---|---|
适用于正式版代码 | 是 | 是 |
服务 | SearchAds360Service |
SearchAds360Service |
场景 | 提取对象和报告 | 提取对象和报告 |
响应 | SearchAds360Row 对象的数据流 |
SearchAds360Row 对象的页面 |
响应的字段 | 仅查询中指定的维度 | 仅查询中指定的维度 |
每日上限 | 请参阅 API 限制和配额。 | 请参阅 API 限制和配额。 |
SearchStream 与 Search
虽然 Search
可以发送多个分页请求来下载整个报告,但 SearchStream
只会发送一个请求,并与 Search Ads 360 Reporting API 建立持久连接(无论报告大小如何)。
对于 SearchStream
,数据包会立即开始下载,整个结果会缓存在数据缓冲区中。您的代码可以开始读取缓冲数据,而无需等待整个数据流完成。
通过消除请求 Search
响应的每个单独页面所需的往返网络时间,SearchStream
的性能可以比分页更出色,具体取决于您的应用,尤其是对于较大的报告。
示例
例如,假设有一个包含 100,000
行的数据报告。下表详细说明了两种方法之间的会计差异。
SearchStream | 搜索 | |
---|---|---|
页面大小 | 不适用 | 每页 10,000 行 |
API 请求数量 | 1 个请求 | 10 个请求 |
API 响应数量 | 1 个连续直播 | 10 个回答 |
性能因素
一般来说,我们建议您使用 SearchStream
,而不是 Search
,原因如下。
对于单页报告(少于 10,000 行):这两种方法的性能没有明显差异。
对于多页报告:
SearchStream
通常速度更快,因为它可以避免多次往返,并且从磁盘缓存读取/写入的影响较小。
速率限制
这两种方法的每日限制均遵循标准的 API 限制和配额。无论结果是分页还是流式传输,单个查询或报告都计为一次操作。
流式传输示例
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sample;
import com.beust.jcommander.Parameter;
import com.google.ads.searchads360.v0.lib.SearchAds360Client;
import com.google.ads.searchads360.v0.services.SearchAds360Row;
import com.google.ads.searchads360.v0.services.SearchAds360ServiceClient;
import com.google.ads.searchads360.v0.services.SearchSearchAds360StreamRequest;
import com.google.ads.searchads360.v0.services.SearchSearchAds360StreamResponse;
import com.google.api.gax.rpc.ServerStream;
/** Get campaign details using SearchStream. */
public class GetCampaignsStream {
private static class GetCampaignsStreamParams extends CodeSampleParams {
@Parameter(names = "--customerId", required = true)
private String customerId;
@Parameter(names = "--loginCustomerId")
private String loginCustomerId;
}
public static void main(String[] args) {
GetCampaignsStreamParams params = new GetCampaignsStreamParams();
if (!params.parseArguments(args)) {
// Optional: You may pass the loginCustomerId on the command line or specify a loginCustomerId
// here (10 digits, no dashes). If neither are set, customerId will be used as
// loginCustomerId.
// params.loginCustomerId = Long.parseLong("INSERT_LOGIN_CUSTOMER_ID_HERE");
}
final String loginCustomerId = params.loginCustomerId;
final String customerId = params.customerId;
try {
// Creates a SearchAds360Client with the specified loginCustomerId. If there's
// no loginCustomerId, customerId will be used instead.
final SearchAds360Client searchAds360Client =
SearchAds360Client.newBuilder()
.setLoginCustomerId(loginCustomerId == null ? customerId : loginCustomerId)
.fromPropertiesFile()
.build();
// Creates the Search Ads 360 Service client.
SearchAds360ServiceClient client = searchAds360Client.create();
new GetCampaignsStream().runExample(client, customerId);
} catch (Exception exception) {
System.err.printf("Failed with exception: %s%n", exception);
exception.printStackTrace();
System.exit(1);
}
}
private void runExample(SearchAds360ServiceClient searchAds360ServiceClient, String customerId) {
// Creates a query that retrieves all campaigns under the customerId.
String query = "SELECT campaign.name, campaign.id, campaign.status FROM campaign";
SearchSearchAds360StreamRequest request =
SearchSearchAds360StreamRequest.newBuilder()
.setCustomerId(customerId)
.setQuery(query)
.build();
// Issues a search stream request.
ServerStream<SearchSearchAds360StreamResponse> stream =
searchAds360ServiceClient.searchStreamCallable().call(request);
for (SearchSearchAds360StreamResponse response : stream) {
for (SearchAds360Row element : response.getResultsList()) {
System.out.printf(
"Campaign found with name '%s', ID %d, and status: %s.%n",
element.getCampaign().getName(),
element.getCampaign().getId(),
element.getCampaign().getStatus());
}
}
}
}
#!/usr/bin/env python
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Retrieves campaigns for a customer using a stream request."""
import argparse
import traceback
from google.ads.searchads360.v0.services.types.search_ads360_service import SearchSearchAds360StreamRequest
from util_searchads360 import SearchAds360Client
def main(client, customer_id) -> None:
search_ads_360_service = client.get_service()
query = """
SELECT
campaign.name,
campaign.id,
campaign.status
FROM campaign"""
request = SearchSearchAds360StreamRequest()
request.customer_id = customer_id
request.query = query
# Issues a search stream request.
results = search_ads_360_service.search_stream(request=request)
for response in results:
for result in response.results:
campaign = result.campaign
print(
f'campaign "{campaign.name}" has id {campaign.id} and status {campaign.status.name}'
)
if __name__ == "__main__":
# SearchAds360Client will read the search-ads-360.yaml configuration file in
# the home directory if none is specified.
search_ads_360_client = SearchAds360Client.load_from_file()
parser = argparse.ArgumentParser(
description=("Retrieves campaigns for a customer."))
# Arguments to provide to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Search Ads 360 customer ID (10 digits, no dashes).",
)
parser.add_argument(
"-l",
"--login_customer_id",
type=str,
required=False,
help="The Search Ads 360 login customer ID (10 digits, no dashes).",
)
args = parser.parse_args()
search_ads_360_client.set_ids(args.customer_id, args.login_customer_id)
try:
main(search_ads_360_client, args.customer_id)
except Exception: # pylint: disable=broad-except
traceback.print_exc()