使用 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.

    后续步骤