簡體   English   中英

如何使用Google Bigquery的Java API以Json形式獲取查詢結果

[英]How to get query result in Json form using Java API of Google Bigquery

我正在使用Google Bigquery V2 Java API。 我無法找到一種以JSON格式獲取查詢結果的方法。 在Bigquery Web用戶界面中,我們可以看到此JSON和Table形式的結果。 參見scrrenshot。

有什么方法可以使用Java API將GetQueryResultsResponse轉換為JSON。 在此處輸入圖片說明

一種選擇是將TO_JSON_STRING函數應用於查詢結果。 例如,

#standardSQL
SELECT TO_JSON_STRING(t)
FROM (
  SELECT x, y
  FROM YourTable
  WHERE z = 10
) AS t;

如果您希望表格的所有列都為JSON,則可以使用一種更簡單的形式:

#standardSQL
SELECT TO_JSON_STRING(t)
FROM YourTable AS t
WHERE z = 10;

我正在使用服務帳戶訪問BigQuery REST API以獲取JSON格式的響應。

為了使用服務帳戶,您將必須轉到憑據( https://console.cloud.google.com/apis/credentials )並選擇一個項目。

點擊憑證按鈕

您將獲得如下所示的下拉列表: 從選項中選擇服務帳戶

為您的項目創建一個服務帳戶,並以JSON格式下載機密文件。 將JSON文件保留在文件系統中,並設置其路徑。 檢查下圖以設置文件路徑:

如圖所示設置密鑰和憑證圖像的路徑

因此,現在您要做的就是使用JAVA客戶端api來使用Big Query REST API。

這是我在項目中一直使用的簡單解決方案。

package com.example.bigquery;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import org.apache.log4j.Logger;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.common.io.CharStreams;

public class BigQueryDemo {

    private static final String QUERY_URL_FORMAT = "https://www.googleapis.com/bigquery/v2/projects/%s/queries" + "?access_token=%s";

    private static final String QUERY = "query";

    private static final String QUERY_HACKER_NEWS_COMMENTS = "SELECT * FROM [bigquery-public-data:hacker_news.comments] LIMIT 1000";

    private static final Logger logger = Logger.getLogger(BigQueryDemo.class);

    static GoogleCredential credential = null;
    static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    static final JsonFactory JSON_FACTORY = new JacksonFactory();
    static {
        // Authenticate requests using Google Application Default credentials.
        try {
            credential = GoogleCredential.getApplicationDefault();
            credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));
            credential.refreshToken();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void implicit() {
        String projectId = credential.getServiceAccountProjectId();
        String accessToken = generateAccessToken();
        // Set the content of the request.
        Dataset dataset = new Dataset().addLabel(QUERY, QUERY_HACKER_NEWS_COMMENTS);
        HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset.getLabels());
        // Send the request to the BigQuery API.
        GenericUrl url = new GenericUrl(String.format(QUERY_URL_FORMAT, projectId, accessToken));
        logger.debug("URL: " + url.toString());
        String responseJson = getQueryResult(content, url);
        logger.debug(responseJson);
    }

    private static String getQueryResult(HttpContent content, GenericUrl url) {
        String responseContent = null;
        HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
        HttpRequest request = null;
        try {
            request = requestFactory.buildPostRequest(url, content);
            request.setParser(JSON_FACTORY.createJsonObjectParser());
            request.setHeaders(
                    new HttpHeaders().set("X-HTTP-Method-Override", "POST").setContentType("application/json"));
            HttpResponse response = request.execute();
            InputStream is = response.getContent();
            responseContent = CharStreams.toString(new InputStreamReader(is));
        } catch (IOException e) {
            logger.error(e);
        }
        return responseContent;
    }

    private static String generateAccessToken() {
        String accessToken = null;
        if ((System.currentTimeMillis() > credential.getExpirationTimeMilliseconds())) {
            accessToken = credential.getRefreshToken();
        } else {
            accessToken = credential.getAccessToken();
        }
        System.out.println(accessToken);
        return accessToken;
    }
}

以下是Github的代碼鏈接: https : //github.com/vslala/BigQueryRestSample

這只是一個演示項目,可從BQ REST API提取JSON數據。 不要在項目中直接使用它。 如果您有任何疑問,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM