0

我正在使用以下代码行从 Google Bigquery 获取数据。

 public class BQTEST {
        public static void main(String... args) throws Exception {
            String datasetName = "mydataset";
            String tableName = "mytable";
            String projectId = "id-gcs";
            String query =
                    "SELECT id, " +
                            "qtr, " +
                            "sales, " +
                            "year " +
                            "FROM `id-gcs.mydataset.mytable` " +
                            "where MOD(id,2) = 0";
            BigQuery bigquery = BigQueryOptions.newBuilder().setProjectId(projectId)
                    .setCredentials(
                            ServiceAccountCredentials.fromStream(new
                                    FileInputStream("gcs.json"))
                    )
                    .build().getService();
            TableId tableId = TableId.of(projectId, datasetName, tableName);
            QueryJobConfiguration queryConfig = QueryJobConfiguration
                    .newBuilder(query)
                    .setPriority(QueryJobConfiguration.Priority.BATCH)
                    .build();
            try {
                bigquery.query(queryConfig);
    
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException(e.getMessage());
            }
            TableResult results = bigquery.listTableData(
                    tableId,
                    BigQuery.TableDataListOption.pageSize(1)
            );
    
    
            for (FieldValueList row : results.iterateAll()) {
                System.out.printf(
                        "ID: %s qtr: %s sales: %s year: %s\n", row.get(0).getValue(), row.get(1).getValue(), row.get(2).getValue(), row.get(3).getValue());
            }
        
        }
    }

我在源表中有 12 条记录,从 1,2,3...12 开始 id 值。由于我在 ID 上应用了 Mod,结果集的 id 值应为 2、4、6、8、10、12。

相反,它将整个数据作为结果集返回。

因此,where 子句中的条件不适用。

寻求帮助。

4

1 回答 1

1

您在这里做了两件不相关的事情:运行查询,然后尝试直接从您刚刚查询的源表中读取行。您没有得到过滤结果的原因是您没有从查询结果中读取行,而是直接从源表中读取行。

经过进一步审查,这似乎是基于一些具有误导性的示例代码;我会解决的。

一个可能更具启发性的简短示例:https ://cloud.google.com/bigquery/docs/samples/bigquery-query#bigquery_query-java

值得注意的是,看看结果迭代器是如何从bigquery.query(). 那是您的过滤结果可用的地方,而不是通过对源表进行迭代。

于 2021-12-30T05:54:25.070 回答