Truyền trực tuyến báo cáo

Có hai phương pháp để truy xuất thực thể và dữ liệu báo cáo thông qua API Báo cáo Search Ads 360.

Hướng dẫn này chủ yếu tập trung vào việc truyền trực tuyến dữ liệu từ SearchAds360Service. Dưới đây là các điểm khác biệt cấp cao cho 2 phương thức truy xuất dữ liệu:

SearchAds360Service.SearchStream SearchAds360Service.Search
Phù hợp với mã sản xuất
Dịch vụ SearchAds360Service SearchAds360Service
Trường hợp Đang tìm nạp đối tượng và báo cáo Đang tìm nạp đối tượng và báo cáo
Phản hồi Luồng của các đối tượng SearchAds360Row Các trang của đối tượng SearchAds360Row
Các trường của câu trả lời Chỉ những giá trị được chỉ định trong truy vấn Chỉ những giá trị được chỉ định trong truy vấn
Giới hạn hằng ngày Xem hạn mức và giới hạn API. Xem hạn mức và giới hạn API.

Mặc dù Search có thể gửi nhiều yêu cầu được phân trang để tải toàn bộ báo cáo xuống, nhưng SearchStream sẽ gửi một yêu cầu duy nhất và bắt đầu kết nối liên tục với API Báo cáo Search Ads 360 bất kể quy mô báo cáo.

Đối với SearchStream, các gói dữ liệu bắt đầu tải xuống ngay lập tức, với toàn bộ kết quả được lưu vào bộ nhớ đệm dữ liệu. Mã của bạn có thể bắt đầu đọc dữ liệu được lưu vào vùng đệm mà không phải đợi toàn bộ luồng kết thúc.

Bằng cách loại bỏ thời gian mạng trọn vòng cần thiết để yêu cầu từng trang riêng lẻ về một phản hồi Search, tuỳ thuộc vào ứng dụng của bạn, SearchStream có thể cải thiện hiệu suất so với phân trang, đặc biệt là đối với các báo cáo lớn hơn.

Ví dụ:

Ví dụ: hãy lấy một báo cáo có chứa 100,000 hàng. Bảng sau đây phân tích sự khác biệt về cách tính giữa hai phương pháp.

SearchStream Tìm kiếm
Kích thước trang Không áp dụng 10.000 hàng trên mỗi trang
Số lượng yêu cầu API 1 yêu cầu 10 yêu cầu
Số lượng phản hồi API 1 luồng phát liên tục 10 câu trả lời

Hệ số hiệu suất

Nói chung, bạn nên dùng SearchStream thay vì Search vì những lý do sau.

  • Đối với các báo cáo trang đơn (dưới 10.000 hàng): Không có sự khác biệt đáng kể về hiệu suất giữa 2 phương thức.

  • Đối với nhiều báo cáo trang: SearchStream thường nhanh hơn vì tránh được nhiều lượt khứ hồi và việc đọc/ghi từ bộ nhớ đệm trên ổ đĩa ít phụ thuộc vào nhiều yếu tố.

Giới hạn số lượng yêu cầu

Giới hạn hằng ngày cho cả hai phương thức đều tuân thủ các giới hạn và hạn mức API tiêu chuẩn. Mỗi truy vấn hoặc báo cáo được tính là một thao tác, bất kể kết quả đó được phân trang hay truyền trực tuyến.

Ví dụ về phát trực tuyến

Java

// 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());
      }
    }
  }
}

Tải xuống GetCampaignsStream.java

Python

#!/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()

Tải get_campaigns_stream.py xuống