Tạo và cập nhật báo cáo

Dịch vụ Báo cáo dành cho API Campaign Manager 360 cho phép bạn tạo và cập nhật báo cáo Trình tạo báo cáo bằng các đối tượng tài nguyên báo cáo. Tài nguyên báo cáo trình bày thông tin cơ bản về báo cáo sẽ chạy, cũng như cấu trúc của báo cáo.

Hướng dẫn này trình bày chi tiết cách tạo và cập nhật báo cáo Trình tạo báo cáo theo phương thức lập trình thông qua dịch vụ Báo cáo.

Định cấu hình tài nguyên báo cáo

Bước đầu tiên trong việc tạo hoặc cập nhật báo cáo Trình tạo báo cáo là định cấu hình đối tượng tài nguyên báo cáo. Nếu đang tạo báo cáo mới, bạn sẽ bắt đầu với một tài nguyên trống và đặt các trường cần thiết. Nếu đang cập nhật một báo cáo hiện có, bạn có thể chọn:

  1. Ưu tiên: Thực hiện cập nhật một phần. Khi sử dụng phương pháp này, bạn sẽ bắt đầu với một tài nguyên trống và đặt các trường mà bạn muốn thay đổi. Cập nhật một phần chỉ lưu thay đổi cho các trường bạn chỉ định.
  2. Cập nhật đầy đủ. Khi sử dụng phương pháp này, bạn sẽ tải một tài nguyên báo cáo hiện có và trực tiếp sửa đổi các trường của tài nguyên đó. Bản cập nhật đầy đủ sẽ luôn lưu tất cả các trường của báo cáo.

Nội dung chính xác của tài nguyên báo cáo khác nhau tùy thuộc vào loại báo cáo bạn đang định cấu hình. Mặc dù vậy, có một vài trường phổ biến cho tất cả các loại báo cáo:

TrườngNội dung mô tả
Các trường bắt buộc
nameTên báo cáo.
loạiLoại báo cáo.
Các trường không bắt buộc
giao hàngCài đặt gửi email của báo cáo.
Tên tệpTên tệp được sử dụng khi tạo tệp báo cáo cho báo cáo này.
định dạngĐịnh dạng đầu ra của báo cáo, ở định dạng CSV hoặc Excel.
lịch biểuLịch biểu dùng để chạy báo cáo của bạn theo định kỳ.

Những trường phổ biến này tạo nên bộ khung của báo cáo. Ví dụ dưới đây minh họa việc tạo tài nguyên báo cáo chuẩn mới:

C#

Report report = new Report();

// Set the required fields "name" and "type".
report.Name = "Example standard report";
report.Type = "STANDARD";

// Set optional fields.
report.FileName = "example_report";
report.Format = "CSV";

Java

Report report = new Report();

// Set the required fields "name" and "type".
report.setName("Example standard report");
report.setType("STANDARD");

// Set optional fields
report.setFileName("example_report");
report.setFormat("CSV");

1.199

$report = new Google_Service_Dfareporting_Report();

// Set the required fields "name" and "type".
$report->setName('Example standard report');
$report->setType('STANDARD');

// Set optional fields.
$report->setFileName('example_report');
$report->setFormat('CSV');

Python

report = {
    # Set the required fields "name" and "type".
    'name': 'Example Standard Report',
    'type': 'STANDARD',
    # Set optional fields.
    'fileName': 'example_report',
    'format': 'CSV'
}

Ruby

report = DfareportingUtils::API_NAMESPACE::Report.new(
  # Set the required fields "name" and "type".
  name: 'Example Standard Report',
  type: 'STANDARD',
  # Set optional fields.
  file_name: 'example_report',
  format: 'CSV'
)

Xác định tiêu chí báo cáo

Khi bạn đã chọn loại báo cáo và định cấu hình các trường thông thường, bước tiếp theo là xác định tiêu chí báo cáo. Tiêu chí báo cáo được sử dụng để giới hạn phạm vi báo cáo của bạn, bảo đảm chỉ thông tin có liên quan được trả lại. Nó cũng xác định cấu trúc của báo cáo đầu ra.

Tiêu chí được sử dụng phụ thuộc vào loại báo cáo. Mối quan hệ giữa loại báo cáo và tiêu chí được giải thích trong bảng sau:

Loại báo cáo Trường tiêu chí
TIÊU CHUẨN tiêu chí
REACH reachtiếp
PATH_TO_CONVERSION pathToConversionCRITERIA
FLOODLIGHT floodlightTiêu chí
CROSS_DIMENSION_REACH crossDimensionReachCRITERIA

Mặc dù mỗi tiêu chí loại cụ thể này hiển thị một tập hợp trường hơi khác, có một tập hợp các trường tiêu chí chung thường hữu ích cho việc kiểm soát đầu ra báo cáo:

Trường Nội dung mô tả
phạm vi ngày Ngày nên chạy báo cáo này. Có thể được sử dụng để xác định ngày bắt đầu và ngày kết thúc tùy chỉnh hoặc phạm vi ngày tương đối.
bộ lọc kích thước Danh sách các bộ lọc hạn chế kết quả trả về. Xem phần giá trị bộ lọc truy vấn để biết thêm thông tin về định cấu hình bộ lọc.
phương diện Danh sách các phần tử Campaign Manager 360 để đưa vào kết quả báo cáo.
Tên số liệu Đơn vị đo lường chuẩn để đưa vào kết quả báo cáo.

Xem phần xác định khả năng tương thích của trường để biết thêm thông tin về cách chọn thứ nguyên, chỉ số và bộ lọc cho báo cáo của bạn. Các trường tiêu chí bổ sung theo loại cụ thể được giải thích trong tài liệu tham khảotrung tâm trợ giúp.

Ví dụ bên dưới thêm tiêu chí cơ bản vào tài nguyên báo cáo chuẩn của chúng tôi:

C#

// Define a date range to report on. This example uses explicit start and
// end dates to mimic the "LAST_30_DAYS" relative date range.
DateRange dateRange = new DateRange();
dateRange.EndDate = DateTime.Now.ToString("yyyy-MM-dd");
dateRange.StartDate = DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd");

// Create a report criteria.
SortedDimension dimension = new SortedDimension();
dimension.Name = "advertiser";

Report.CriteriaData criteria = new Report.CriteriaData();
criteria.DateRange = dateRange;
criteria.Dimensions = new List<SortedDimension>() { dimension };
criteria.MetricNames = new List<string>() {
  "clicks",
  "impressions"
};

// Add the criteria to the report resource.
report.Criteria = criteria;

Java

// Define a date range to report on. This example uses explicit start and end dates to mimic
// the "LAST_MONTH" relative date range.
DateRange dateRange = new DateRange();
dateRange.setEndDate(new DateTime(true, System.currentTimeMillis(), null));

Calendar lastMonth = Calendar.getInstance();
lastMonth.add(Calendar.MONTH, -1);
dateRange.setStartDate(new DateTime(true, lastMonth.getTimeInMillis(), null));

// Create a report criteria.
Report.Criteria criteria = new Report.Criteria();
criteria.setDateRange(dateRange);
criteria.setDimensions(Lists.newArrayList(new SortedDimension().setName("advertiser")));
criteria.setMetricNames(Lists.newArrayList("clicks", "impressions"));

// Add the criteria to the report resource.
report.setCriteria(criteria);

1.199

// Define a date range to report on. This example uses explicit start and
// end dates to mimic the "LAST_30_DAYS" relative date range.
$dateRange = new Google_Service_Dfareporting_DateRange();
$dateRange->setStartDate(
    date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') - 30, date('Y')))
);
$dateRange->setEndDate(date('Y-m-d'));

// Create a report criteria.
$dimension = new Google_Service_Dfareporting_SortedDimension();
$dimension->setName('advertiser');

$criteria = new Google_Service_Dfareporting_ReportCriteria();
$criteria->setDateRange($dateRange);
$criteria->setDimensions([$dimension]);
$criteria->setMetricNames(['clicks', 'impressions']);

// Add the criteria to the report resource.
$report->setCriteria($criteria);

Python

# Define a date range to report on. This example uses explicit start and end
# dates to mimic the "LAST_30_DAYS" relative date range.
end_date = date.today()
start_date = end_date - timedelta(days=30)

# Create a report criteria.
criteria = {
    'dateRange': {
        'startDate': start_date.strftime('%Y-%m-%d'),
        'endDate': end_date.strftime('%Y-%m-%d')
    },
    'dimensions': [{
        'name': 'advertiser'
    }],
    'metricNames': ['clicks', 'impressions']
}

# Add the criteria to the report resource.
report['criteria'] = criteria

Ruby

# Define a date range to report on. This example uses explicit start and end
# dates to mimic the "LAST_30_DAYS" relative date range.
start_date = DateTime.now.prev_day(30).strftime('%Y-%m-%d')
end_date = DateTime.now.strftime('%Y-%m-%d')

# Create a report criteria
criteria = DfareportingUtils::API_NAMESPACE::Report::Criteria.new(
  date_range: DfareportingUtils::API_NAMESPACE::DateRange.new(
    start_date: start_date,
    end_date: end_date
  ),
  dimensions: [
    DfareportingUtils::API_NAMESPACE::SortedDimension.new(
      name: 'advertiser'
    )
  ],
  metric_names: ['clicks', 'impressions']
)

# Add the criteria to the report resource.
report.criteria = criteria

Giá trị bộ lọc truy vấn

Khi định cấu hình bộ lọc cho báo cáo, bạn cần phải chỉ định giá trị chính xác mà các bộ lọc sẽ sử dụng để hạn chế đầu ra báo cáo. Nếu bạn không chắc chắn các giá trị có thể có cho một bộ lọc cụ thể là gì, hãy tìm các giá trị đó bằng dịch vụ DimensionValues.

Truy vấn giá trị phương diện cơ bản chứa tên phương diện, cũng như ngày bắt đầungày kết thúc. Ngày bắt đầu và ngày kết thúc giới hạn phản hồi cho các giá trị hợp lệ trong khoảng thời gian đó. Bạn có thể chỉ định Bộ lọc bổ sung nếu cần giới hạn kết quả truy vấn hơn nữa.

Ví dụ bên dưới tra cứu giá trị bộ lọc nhà quảng cáo hợp lệ trong các ngày báo cáo của chúng tôi sẽ chạy và thêm chúng vào tiêu chí báo cáo:

C#

// Query advertiser dimension values for report run dates.
DimensionValueRequest request = new DimensionValueRequest();
request.StartDate = report.Criteria.DateRange.StartDate;
request.EndDate = report.Criteria.DateRange.EndDate;
request.DimensionName = "advertiser";

DimensionValueList values =
    service.DimensionValues.Query(request, profileId).Execute();

if (values.Items.Any()) {
  // Add a value as a filter to the report criteria.
  report.Criteria.DimensionFilters = new List<DimensionValue>() {
    values.Items[0]
  };
}

Java

// Query advertiser dimension values for report run dates.
DimensionValueRequest request = new DimensionValueRequest();
request.setStartDate(report.getCriteria().getDateRange().getStartDate());
request.setEndDate(report.getCriteria().getDateRange().getEndDate());
request.setDimensionName("advertiser");

DimensionValueList values = reporting.dimensionValues().query(profileId, request).execute();

if (!values.getItems().isEmpty()) {
  // Add a value as a filter to the report criteria.
  List<DimensionValue> filters = Lists.newArrayList(values.getItems().get(0));
  report.getCriteria().setDimensionFilters(filters);
}

1.199

// Query advertiser dimension values for report run dates.
$request = new Google_Service_Dfareporting_DimensionValueRequest();
$request->setStartDate(
    $report->getCriteria()->getDateRange()->getStartDate()
);
$request->setEndDate(
    $report->getCriteria()->getDateRange()->getEndDate()
);
$request->setDimensionName('advertiser');

$values =
    $this->service->dimensionValues->query($userProfileId, $request);

if (!empty($values->getItems())) {
    // Add a value as a filter to the report criteria.
    $report->getCriteria()->setDimensionFilters([$values->getItems()[0]]);
}

Python

# Query advertiser dimension values for report run dates.
request = {
    'dimensionName': 'advertiser',
    'endDate': report['criteria']['dateRange']['endDate'],
    'startDate': report['criteria']['dateRange']['startDate']
}

values = service.dimensionValues().query(
    profileId=profile_id, body=request).execute()

if values['items']:
  # Add a value as a filter to the report criteria.
  report['criteria']['dimensionFilters'] = [values['items'][0]]

Ruby

# Query advertiser dimension values for report run dates.
dimension = DfareportingUtils::API_NAMESPACE::DimensionValueRequest.new(
  dimension_name: 'advertiser',
  start_date: report.criteria.date_range.start_date,
  end_date: report.criteria.date_range.end_date
)

values = service.query_dimension_value(profile_id, dimension)

unless values.items.empty?
  # Add a value as a filter to the report criteria.
  report.criteria.dimension_filters = [values.items.first]
end

Xác định khả năng tương thích của trường

Khi định cấu hình tiêu chí báo cáo của bạn, điều quan trọng cần nhớ là không phải tất cả các kết hợp số liệu, thứ nguyên và bộ lọc đều hợp lệ. Bạn sẽ không được phép lưu báo cáo chứa kết hợp không hợp lệ, vì vậy, điều quan trọng là phải đảm bảo các trường mà bạn dự định sử dụng tương thích với nhau.

Khi tạo tài nguyên báo cáo, bạn có thể chuyển tài nguyên đó vào dịch vụ Reports.compatibleFields để xem trường nào hợp lệ với những trường bạn đã chọn. Cấu hình của báo cáo sẽ được phân tích và phản hồi chứa thứ nguyên, chỉ số và bộ lọc tương thích sẽ được trả về. Vì các trường trong phản hồi này không đảm bảo tương thích với nhau, có thể bạn cần thực hiện nhiều yêu cầu để đảm bảo tất cả các trường bạn chọn sẽ hoạt động cùng nhau.

Ví dụ bên dưới minh họa cách đưa ra yêu cầu trường tương thích mẫu, sử dụng tài nguyên báo cáo của chúng tôi làm dữ liệu đầu vào:

C#

CompatibleFields fields =
    service.Reports.CompatibleFields.Query(report, profileId).Execute();

ReportCompatibleFields reportFields = fields.ReportCompatibleFields;

if(reportFields.Dimensions.Any()) {
  // Add a compatible dimension to the report.
  Dimension dimension = reportFields.Dimensions[0];
  SortedDimension sortedDimension = new SortedDimension();
  sortedDimension.Name = dimension.Name;
  report.Criteria.Dimensions.Add(sortedDimension);
} else if (reportFields.Metrics.Any()) {
  // Add a compatible metric to the report.
  Metric metric = reportFields.Metrics[0];
  report.Criteria.MetricNames.Add(metric.Name);
}

Java

CompatibleFields fields = reporting.reports().compatibleFields()
    .query(profileId, report).execute();

ReportCompatibleFields reportFields = fields.getReportCompatibleFields();

if (!reportFields.getDimensions().isEmpty()) {
  // Add a compatible dimension to the report.
  Dimension dimension = reportFields.getDimensions().get(0);
  SortedDimension sortedDimension = new SortedDimension().setName(dimension.getName());
  report.getCriteria().getDimensions().add(sortedDimension);
} else if (!reportFields.getMetrics().isEmpty()) {
  // Add a compatible metric to the report.
  Metric metric = reportFields.getMetrics().get(0);
  report.getCriteria().getMetricNames().add(metric.getName());
}

1.199

$fields = $this->service->reports_compatibleFields->query(
    $userProfileId,
    $report
);

$reportFields = $fields->getReportCompatibleFields();

if (!empty($reportFields->getDimensions())) {
    // Add a compatible dimension to the report.
    $dimension = $reportFields->getDimensions()[0];
    $sortedDimension = new Google_Service_Dfareporting_SortedDimension();
    $sortedDimension->setName($dimension->getName());
    $report->getCriteria()->setDimensions(
        array_merge(
            $report->getCriteria()->getDimensions(),
            [$sortedDimension]
        )
    );
} elseif (!empty($reportFields->getMetrics())) {
    // Add a compatible metric to the report.
    $metric = $reportFields->getMetrics()[0];
    $report->getCriteria()->setMetricNames(
        array_merge(
            $report->getCriteria()->getMetricNames(),
            [$metric->getName()]
        )
    );
}

Python

fields = service.reports().compatibleFields().query(
    profileId=profile_id, body=report).execute()

report_fields = fields['reportCompatibleFields']

if report_fields['dimensions']:
  # Add a compatible dimension to the report.
  report['criteria']['dimensions'].append({
      'name': report_fields['dimensions'][0]['name']
  })
elif report_fields['metrics']:
  # Add a compatible metric to the report.
  report['criteria']['metricNames'].append(
      report_fields['metrics'][0]['name'])

Ruby

fields = service.query_report_compatible_field(profile_id, report)

report_fields = fields.report_compatible_fields

if report_fields.dimensions.any?
  # Add a compatible dimension to the report.
  report.criteria.dimensions <<
    DfareportingUtils::API_NAMESPACE::SortedDimension.new(
      name: report_fields.dimensions.first.name
    )
elsif report_fields.metrics.any?
  # Add a compatible metric to the report.
  report.criteria.metric_names << report_fields.metrics.first.name
end

Lưu báo cáo

Bước cuối cùng trong quy trình này là lưu tài nguyên báo cáo. Nếu đang tạo báo cáo mới, bạn có thể chèn báo cáo đó bằng lệnh gọi đến Reports.insert:

C#

Report insertedReport =
    service.Reports.Insert(report, profileId).Execute();

Java

Report insertedReport = reporting.reports().insert(profileId, report).execute();

1.199

$insertedReport =
    $this->service->reports->insert($userProfileId, $report);

Python

inserted_report = service.reports().insert(
    profileId=profile_id, body=report).execute()

Ruby

report = service.insert_report(profile_id, report)

Nếu đang cập nhật một phần, bạn có thể lưu các thay đổi của mình bằng cách gọi Reports.patch:

C#

// Patch an existing report.
Report patchedReport =
    service.Reports.Patch(report, profileId, reportId).Execute();

Java

// Patch an existing report.
Report patchedReport = reporting.reports().patch(profileId, reportId, report).execute();

1.199

# Patch an existing report.
$patchedReport =
    $this->service->reports->patch($userProfileId, $reportId, $report)

Python

# Patch an existing report.
patched_report = service.reports().patch(
    profileId=profile_id, reportId=report_id, body=report).execute();

Ruby

# Patch an existing report.
patched_report = service.patch_report(profile_id, report_id, report)

Hoặc, nếu đã quyết định thực hiện cập nhật đầy đủ, bạn có thể lưu thay đổi bằng cách gọi Reports.update:

C#

// Update an existing report.
Report updatedReport =
    service.Reports.Update(report, profileId, report.Id).Execute();

Java

// Update an existing report.
Report updatedReport = reporting.reports().update(profileId, report.getId(), report).execute();

1.199

# Update an existing report.
$updatedReport =
    $this->service->reports->update($userProfileId, $report->getId(), $report)

Python

# Update an existing report.
updated_report = service.reports().update(
    profileId=profile_id, reportId=report['id'], body=report).execute();

Ruby

# Update an existing report.
updated_report = service.update_report(profile_id, report.id, report);

Sau khi yêu cầu lưu thành công, bản sao của tài nguyên báo cáo sẽ được trả về nội dung phản hồi. Tài nguyên này sẽ có một vài trường mới được điền, trong đó quan trọng nhất là trường id. Đây là mã bạn sẽ dùng để tham chiếu đến báo cáo này trong suốt phần còn lại của quy trình làm việc.