如何使用google-cloud-bigquery库从Android运行BigQuery查询

时间:2019-05-16 09:03:04

标签: android firebase google-bigquery firebase-analytics

我想从BigQuery事件表中获取数据到我的android设备中。

我尝试使用BigQuery库,但是即使我尝试使用credential.json文件也无法正常工作,但仍无法正常工作。 实施'com.google.cloud:google-cloud-bigquery:1.73.0'

如果您可以详细说明或共享一些参考链接以从android设备运行查询,请给我该链接。

谢谢。

try {
        // Instantiate a client.
        BigQuery bigquery = BigQueryOptions.newBuilder().setCredentials(credential).build().getService();*/
        BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
        QueryJobConfiguration queryConfig =
                QueryJobConfiguration.newBuilder(
                        "SELECT "
                                + "param1.value.string_value AS item_name,"
                                + "SUM(param2.value.double_value) AS quantity"
                                + "FROM `uniorder-prod.analytics_200255431.events_*`,"
                                + "UNNEST(event_params) AS param1,"
                                + "UNNEST(event_params) AS param2"
                                + "WHERE event_name = \"total_consumption_res\" AND"
                                + "param1.key = \"item_name\" AND"
                                + "param2.key = \"quantity\""
                                + "GROUP BY item_name"
                                + "ORDER BY quantity DESC")
                        // Use standard SQL syntax for queries.
                        // See: https://cloud.google.com/bigquery/sql-reference/
                        .setUseLegacySql(false)
                        .build();

        // Create a job ID so that we can safely retry.
        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) {
            // You can also look at queryJob.getStatus().getExecutionErrors() for all
            // errors, not just the latest one.
            throw new RuntimeException(queryJob.getStatus().getError().toString());
        }

        // Get the results.
        QueryResponse response = bigquery.getQueryResults(jobId);

        TableResult result = queryJob.getQueryResults();

        // Print all pages of the results.
        for (FieldValueList row : result.iterateAll()) {
            String item_name = row.get("item_name").getStringValue();
            double quantity = row.get("quantity").getDoubleValue();
            System.out.printf("item_name: %s quantity: %d%n", item_name, quantity);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

0 个答案:

没有答案