使用 bq 工具查詢公開資料集

瞭解如何透過 bq 指令列工具檢查及查詢公開資料集。

事前準備

  1. In the Trusted Cloud console, on the project selector page, select or create a Trusted Cloud project.

    Go to project selector

  2. Verify that billing is enabled for your Trusted Cloud project.

  3. 如果在本教學課程中使用的 Trusted Cloud 專案未啟用計費功能,您需要在 BigQuery 沙箱中使用資料。BigQuery 沙箱可讓您學習 BigQuery,但可免費使用的 BigQuery 功能有限。

  4. 確認已啟用 BigQuery API。

    啟用 API

    如果您建立新專案,系統會自動啟用 BigQuery API。

  5. In the Trusted Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Trusted Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  6. 檢查公開資料集

    BigQuery 在 bigquery-public-data.samples 資料集提供多個範例資料表供您查詢。您會在這個教學課程對 shakespeare 資料表執行查詢,資料表內含各齣莎士比亞戲劇的所有字詞。

    查閱 samples 資料集內的 shakespeare 資料表:

    bq show bigquery-public-data:samples.shakespeare
    

    輸出結果會與下列內容相似:系統會省略某些資料欄,以便簡化輸出結果。

      Last modified                  Schema                 Total Rows   Total Bytes
    ----------------- ------------------------------------ ------------ ------------
     14 Mar 17:16:45   |- word: string (required)           164656       6432064
                       |- word_count: integer (required)
                       |- corpus: string (required)
                       |- corpus_date: integer (required)
    

    查詢公開資料集

    使用 bq query 指令,對資料執行 SQL 查詢。

    1. 判斷子字串 raisin 在莎士比亞作品出現的次數:

      bq query --use_legacy_sql=false \
          'SELECT
            word,
            SUM(word_count) AS count
          FROM
            `bigquery-public-data.samples.shakespeare`
          WHERE
            word LIKE "%raisin%"
          GROUP BY
            word;'
      

      輸出結果會與下列內容相似:

      +---------------+-------+
      |     word      | count |
      +---------------+-------+
      | praising      |     8 |
      | Praising      |     4 |
      | raising       |     5 |
      | dispraising   |     2 |
      | dispraisingly |     1 |
      | raisins       |     1 |
      +---------------+-------+
      
    2. 在莎士比亞的作品搜尋子字串 huzzah

      bq query --use_legacy_sql=false \
          'SELECT
            word
          FROM
            `bigquery-public-data.samples.shakespeare`
          WHERE
            word = "huzzah";'
      

      這個子字串未出現在莎士比亞的作品,因此不會傳回結果。

    清除所用資源

    如要避免系統向您的 Trusted Cloud 帳戶收取本頁面所用資源的費用,請刪除含有這些資源的 Trusted Cloud 專案。

    刪除專案

    如果您使用 BigQuery 沙箱查詢公開資料集,表示專案未啟用帳單功能。

    如要避免付費,最簡單的方法就是刪除您為了本教學課程所建立的專案。

    如要刪除專案:

    1. In the Trusted Cloud console, go to the Manage resources page.

      Go to Manage resources

    2. In the project list, select the project that you want to delete, and then click Delete.
    3. In the dialog, type the project ID, and then click Shut down to delete the project.

    後續步驟