首页 > 解决方案 > 从 Java 应用程序调用 getQueryResults 方法时,如何从 QueryResponse 访问 Schema?

问题描述

我正在使用 google.cloud.bigquery 库使用bigquery.query()方法执行和创建查询。我想Schema从响应中获取详细信息,但是每当查询没有返回结果时,我得到EmptyTableResult的不是应该包含的响应Schema和其中列出的字段。我使用了另一种创建作业然后使用查询作业的方法,我正在调用bigquery.getQueryResults它应该返回QueryResponse对象。下面是代码片段。

QueryJobConfiguration queryConfig = 
QueryJobConfiguration.newBuilder(queryString)

.setDefaultDataset(bqDatasetId).setUseLegacySql(false)

 .setFlattenResults(true).build();

JobId jobId = JobId.of(UUID.randomUUID().toString());
        Job queryJob = bigQuery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());

        // Wait for the query to complete.
        queryJob = queryJob.waitFor();

        // Check for errors
        if (queryJob == null) {
          throw new RuntimeException("Job no longer exists");
        } else if (queryJob.getStatus().getError() != null) {
          throw new RuntimeException(queryJob.getStatus().getError().toString());
        }

        // Get the results.
        QueryResponse response = bigQuery.getQueryResults(queryJob.getJobId());
        System.out.println(response);

在这里,在sysout声明中,我得到了正确的响应,但是每当我尝试使用时response.getSchema(),它都会给我编译错误getSchema(),说不可见。谁能帮我这个?这种方法是正确的还是有其他方法可以做同样的事情?

标签: javagoogle-cloud-platformgoogle-bigquery

解决方案


您需要改为调用getQueryResults()Job对象。这会给你一个TableResult对象。然后,您可以调用getSchema()以获取查询/表/作业的架构。所以,把它们放在一起:

QueryJobConfiguration queryConfig =
                QueryJobConfiguration.newBuilder(
                        "SELECT "
                                + "CONCAT('https://stackoverflow.com/questions/', CAST(id as STRING)) as url, "
                                + "view_count "
                                + "FROM `bigquery-public-data.stackoverflow.posts_questions` "
                                + "WHERE tags like '%google-bigquery%' "
                                + "ORDER BY favorite_count DESC LIMIT 10")
                        .setUseLegacySql(false)
                        .build();

        JobId jobId = JobId.of(UUID.randomUUID().toString());
        Job queryJob = BIGQUERY.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
        queryJob = queryJob.waitFor();

        TableResult result = queryJob.getQueryResults(); //<--you need this
        Schema schema = result.getSchema(); //<--..and this

        System.out.println(schema);

产生:

Connected to the target VM, address: '127.0.0.1:64695', transport: 'socket'
Schema{fields=[Field{name=url, type=STRING, mode=NULLABLE, description=null}, Field{name=view_count, type=INTEGER, mode=NULLABLE, description=null}]}

推荐阅读