在 Azure Cosmos DB for PostgreSQL 中執行查詢

適用於: Azure Cosmos DB for PostgreSQL (由 PostgreSQL 的 Citus 資料庫延伸模組提供)

必要條件

若要遵循此快速入門,您首先必須:

  1. 在 Azure 入口網站中建立叢集
  2. 使用 psql 連線至叢集以執行 SQL 命令。
  3. 使用我們的範例資料集建立和散發資料表

分散式查詢

現在進入到快速入門系列的有趣部分 - 執行查詢。 讓我們從簡單的 count (*) 開始,確認我們在上一節中載入的資料量。

-- count all rows (across shards)

SELECT count(*) FROM github_users;
 count
--------
 264308
(1 row)

回想一下,github_users 是分散式資料表,這表示其資料會在多個分區之間分割。 Azure Cosmos DB for PostgreSQL 會自動平行執行所有分區的計數,並合併結果。

讓我們繼續查看更多查詢範例:

-- Find all events for a single user.
-- (A common transactional/operational query)

SELECT created_at, event_type, repo->>'name' AS repo_name
  FROM github_events
 WHERE user_id = 3861633;
     created_at      |  event_type  |              repo_name
---------------------+--------------+--------------------------------------
 2016-12-01 06:28:44 | PushEvent    | sczhengyabin/Google-Image-Downloader
 2016-12-01 06:29:27 | CreateEvent  | sczhengyabin/Google-Image-Downloader
 2016-12-01 06:36:47 | ReleaseEvent | sczhengyabin/Google-Image-Downloader
 2016-12-01 06:42:35 | WatchEvent   | sczhengyabin/Google-Image-Downloader
 2016-12-01 07:45:58 | IssuesEvent  | sczhengyabin/Google-Image-Downloader
(5 rows)

更複雜的查詢

以下是更複雜的查詢範例,會擷取 GitHub 上推送事件的每小時統計資料。 會使用 PostgreSQL 的 JSONB 功能來處理半結構化資料。

-- Querying JSONB type. Query is parallelized across nodes.
-- Find the number of commits on the default branch per hour 

SELECT date_trunc('hour', created_at) AS hour,
       sum((payload->>'distinct_size')::int) AS num_commits
FROM   github_events
WHERE  event_type = 'PushEvent' AND
       payload @> '{"ref":"refs/heads/master"}'
GROUP BY hour
ORDER BY hour;
        hour         | num_commits
---------------------+-------------
 2016-12-01 05:00:00 |       13051
 2016-12-01 06:00:00 |       43480
 2016-12-01 07:00:00 |       34254
 2016-12-01 08:00:00 |       29307
(4 rows)

Azure Cosmos DB for PostgreSQL 會結合 SQL 和 NoSQL 資料存放區處理結構化和半結構化資料的強大功能。

除了執行查詢之外,Azure Cosmos DB for PostgreSQL 也會在分散式資料表的分區上套用資料定義變更:

-- DDL commands that are also parallelized

ALTER TABLE github_users ADD COLUMN dummy_column integer;

下一步

您已成功建立可調整的叢集、建立資料表、加以散發、載入資料,以及執行分散式查詢。

現在您已準備好了解如何使用 Azure Cosmos DB for PostgreSQL 來建置應用程式。