java - 从 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()
,说不可见。谁能帮我这个?这种方法是正确的还是有其他方法可以做同样的事情?
解决方案
您需要改为调用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}]}
推荐阅读
- python - 表情符号到 unicode
- python - 同一字符之间的子字符串 pandas 列
- python - 尽管某些预测不正确,为什么 AUC 等于 1?
- python - Python String .strip() 函数返回错误输出
- laravel-5 - 在 laravel 中安装后如何设置 ckfinder 以显示图像文件夹?
- visual-c++ - 在 UWP 的 C++/WinRT 中,为什么没有明显原因多次调用数据上下文更改事件处理程序
- koa - 为什么我不能在第二个中间件中使用 async 和 await ?
- json - Flutter 中的 SignalR json api 问题 (FormatException: Unexpected character (at character 4)
- python - xpath 中的地址属性(都柏林核心)
- selenium - 选择一个元素的祖先有一个按钮的孩子