如何使用带有Google Client lib for Java的pageTokens请求分页的BigQuery查询结果?

时间:2013-02-11 07:36:18

标签: google-bigquery google-api-java-client

我想运行具有数千行总结果的BigQuery查询,但我只希望一次检索100个结果的页面(使用maxResultspageToken参数)。

BigQuery API支持在pageToken方法上使用collection.list参数。但是,我正在运行异步查询并使用getQueryResult方法检索结果,并且它似乎不支持pageToken参数。是否可以将pageTokengetQueryResults一起使用?

1 个答案:

答案 0 :(得分:11)

更新:有关于如何page through list results here的新文档。

我正在回答这个问题,因为开发人员私下问我这个问题,我想在Stack Overflow上分享答案。

在从Tabledata.list方法请求分页结果时,可以使用pageToken参数。例如,当结果数据超过100k行或10 MB结果时,结果集会自动分页。您还可以通过显式设置maxResults参数来请求结果分页。每个结果页面都会返回一个pageToken参数,然后可以使用该参数检索下一页结果。

每个查询都会生成一个新的BigQuery表。如果您没有明确地命名表格,它只会持续24小时。但是,即使未命名的“匿名”表也有标识符。在任何一种情况下,在插入查询作业后,检索新创建的表的名称。然后使用tabledata.list方法(以及maxResults / pageToken参数的组合)以分页形式请求结果。循环并继续使用先前检索到的pageToken调用tabledata.list,直到不再返回pageTokens(意味着您已到达最后一页。

使用适用于Java的Google API客户端库,插入查询作业,轮询查询完成,然后逐页检索查询结果的代码可能如下所示:

// Create a new BigQuery client authorized via OAuth 2.0 protocol
// See: https://developers.google.com/bigquery/docs/authorization#installed-applications
Bigquery bigquery = createAuthorizedClient();

// Start a Query Job
String querySql = "SELECT TOP(word, 500), COUNT(*) FROM publicdata:samples.shakespeare";
JobReference jobId = startQuery(bigquery, PROJECT_ID, querySql);

// Poll for Query Results, return result output
TableReference completedJob = checkQueryResults(bigquery, PROJECT_ID, jobId);

// Return and display the results of the Query Job
displayQueryResults(bigquery, completedJob);

/**
 * Inserts a Query Job for a particular query
 */
public static JobReference startQuery(Bigquery bigquery, String projectId,
                                      String querySql) throws IOException {
  System.out.format("\nInserting Query Job: %s\n", querySql);

  Job job = new Job();
  JobConfiguration config = new JobConfiguration();
  JobConfigurationQuery queryConfig = new JobConfigurationQuery();
  config.setQuery(queryConfig);

  job.setConfiguration(config);
  queryConfig.setQuery(querySql);

  Insert insert = bigquery.jobs().insert(projectId, job);
  insert.setProjectId(projectId);
  JobReference jobId = insert.execute().getJobReference();

  System.out.format("\nJob ID of Query Job is: %s\n", jobId.getJobId());

  return jobId;
}

/**
 * Polls the status of a BigQuery job, returns TableReference to results if "DONE"
 */
private static TableReference checkQueryResults(Bigquery bigquery, String projectId, JobReference jobId)
    throws IOException, InterruptedException {
  // Variables to keep track of total query time
  long startTime = System.currentTimeMillis();
  long elapsedTime;

  while (true) {
    Job pollJob = bigquery.jobs().get(projectId, jobId.getJobId()).execute();
    elapsedTime = System.currentTimeMillis() - startTime;
    System.out.format("Job status (%dms) %s: %s\n", elapsedTime,
        jobId.getJobId(), pollJob.getStatus().getState());
    if (pollJob.getStatus().getState().equals("DONE")) {
      return pollJob.getConfiguration().getQuery().getDestinationTable();
    }
    // Pause execution for one second before polling job status again, to
    // reduce unnecessary calls to the BigQUery API and lower overall
    // application bandwidth.
    Thread.sleep(1000);
  }
}

/**
 * Page through the result set
 */
private static void displayQueryResults(Bigquery bigquery,
                                        TableReference completedJob) throws IOException {

    long maxResults = 20;
    String pageToken = null;
    int page = 1;

  // Default to not looping
    boolean moreResults = false;

    do {
    TableDataList queryResult = bigquery.tabledata().list(
            completedJob.getProjectId(),
            completedJob.getDatasetId(),
            completedJob.getTableId())
                .setMaxResults(maxResults)
                .setPageToken(pageToken)
         .execute();
    List<TableRow> rows = queryResult.getRows();
    System.out.print("\nQuery Results, Page #" + page + ":\n------------\n");
    for (TableRow row : rows) {
      for (TableCell field : row.getF()) {
      System.out.printf("%-50s", field.getV());
       }
      System.out.println();
    }
    if (queryResult.getPageToken() != null) {
      pageToken = queryResult.getPageToken();
      moreResults = true;
      page++;
    } else {
      moreResults = false;
    }
  } while (moreResults);
}