> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-8a08bda2.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Managed Postgres 快速入门

> 体验 NVMe 加持的 Postgres 性能，并通过原生 ClickHouse 集成实现实时分析

export const Image = ({img, alt, size}) => {
  return <Frame>
      <img src={img} alt={alt} />
    </Frame>;
};

export const galaxyOnClick = eventName => () => {
  try {
    if (typeof window !== "undefined" && window.galaxy && eventName) {
      window.galaxy.track(eventName, {
        interaction: "click"
      });
    }
  } catch (e) {}
};

export const BetaBadge = ({link, galaxyTrack, galaxyEvent}) => {
  if (link) {
    return <a href={link} target="_blank" rel="noopener noreferrer" className="betaBadge" onClick={galaxyTrack && galaxyEvent ? galaxyOnClick(galaxyEvent) : undefined}>
                <Icon />
                <span>Beta</span>
            </a>;
  }
  return <div className="betaBadge">
            <Icon />
            <span>
                Beta feature. 
                <u>
                    <a href="/docs/beta-and-experimental-features#beta-features">
                        Learn more.
                    </a>
                </u>
            </span>
        </div>;
};

ClickHouse Managed Postgres 是采用 NVMe 存储的企业级 Postgres，与 EBS 等网络附加存储相比，可为磁盘受限型工作负载带来最高 10 倍的性能提升。本快速入门分为两个部分：

* **Part 1:** 开始使用 NVMe Postgres，并体验其性能
* **Part 2:** 通过与 ClickHouse 集成，解锁实时分析能力

Managed Postgres 目前已在 AWS 的多个区域提供，并在私有预览期间免费。

**在本快速入门中，您将：**

* 创建一个采用 NVMe 存储、具备高性能的 Managed Postgres 实例
* 加载 100 万条样本事件，亲自体验 NVMe 的速度
* 运行查询，体验低延迟性能
* 将数据复制到 ClickHouse，实现实时分析
* 使用 `pg_clickhouse` 直接从 Postgres 查询 ClickHouse

<div id="part-1">
  ## 第 1 部分：开始使用 NVMe Postgres
</div>

<div id="create-postgres-database">
  ### 创建数据库
</div>

要创建新的 Managed Postgres 服务，请在 Cloud Console 的服务列表中点击 **New service** 按钮。然后即可选择 Postgres 作为数据库类型。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/create-service.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=b91ca25f19bdab7a605c3f2ad0d92d68" alt="创建 Managed Postgres 服务" size="md" border width="1666" height="1634" data-path="images/managed-postgres/create-service.png" />

为数据库实例输入名称，然后点击 **Create service**。随后会进入概览页面。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/overview.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=8a14b55e7cf71cbc81c440902e8728e2" alt="Managed Postgres 概览" size="md" border width="3680" height="2324" data-path="images/managed-postgres/overview.png" />

您的 Managed Postgres 实例将在 3 到 5 分钟内完成预配并可供使用。

<div id="connect">
  ### 连接到你的数据库
</div>

在左侧边栏中，你会看到一个 [**Connect** 按钮](/zh/products/managed-postgres/connection)。点击该按钮即可查看连接信息以及多种格式的连接字符串。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/connect-modal.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=3b804430de4f44a121824a96618d78a8" alt="Managed Postgres 连接弹窗" size="md" border width="1910" height="1728" data-path="images/managed-postgres/connect-modal.png" />

复制 `psql` 连接字符串并连接到你的数据库。你也可以使用任何兼容 Postgres 的客户端 (如 DBeaver) 或任何应用程序库。

<div id="nvme-performance">
  ### 体验 NVMe 性能
</div>

下面来实际感受一下 NVMe 带来的性能提升。首先，在 psql 中启用计时功能，以测量查询执行时间：

```sql theme={null}
\timing
```

创建两个示例表，分别用于事件和用户：

```sql theme={null}
CREATE TABLE events (
   event_id SERIAL PRIMARY KEY,
   event_name VARCHAR(255) NOT NULL,
   event_type VARCHAR(100),
   event_timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
   event_data JSONB,
   user_id INT,
   user_ip INET,
   is_active BOOLEAN DEFAULT TRUE,
   created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
   updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE users (
   user_id SERIAL PRIMARY KEY,
   name VARCHAR(100),
   country VARCHAR(50),
   platform VARCHAR(50)
);
```

现在，插入 100 万条事件，看看 NVMe 的速度：

```sql theme={null}
INSERT INTO events (event_name, event_type, event_timestamp, event_data, user_id, user_ip)
SELECT
   'Event ' || gs::text AS event_name,
   CASE
       WHEN random() < 0.5 THEN 'click'
       WHEN random() < 0.75 THEN 'view'
       WHEN random() < 0.9 THEN 'purchase'
       WHEN random() < 0.98 THEN 'signup'
       ELSE 'logout'
   END AS event_type,
   NOW() - INTERVAL '1 day' * (gs % 365) AS event_timestamp,
   jsonb_build_object('key', 'value' || gs::text, 'additional_info', 'info_' || (gs % 100)::text) AS event_data,
   GREATEST(1, LEAST(1000, FLOOR(POWER(random(), 2) * 1000) + 1)) AS user_id,
   ('192.168.1.' || ((gs % 254) + 1))::inet AS user_ip
FROM
   generate_series(1, 1000000) gs;
```

```text theme={null}
INSERT 0 1000000
时间：3596.542 ms (00:03.597)
```

<Tip>
  **NVMe 性能**

  在不到 4 秒的时间内插入 100 万行 JSONB 数据。在使用 EBS 等网络附加存储的传统云数据库中，由于网络往返延迟和 IOPS 限流，同样的操作通常要多花 2 到 3 倍的时间。NVMe 存储将存储设备直接与计算资源物理连接，从而消除这些瓶颈。

  性能会因实例规格、当前负载和数据特征而异。
</Tip>

插入 1,000 个用户：

```sql theme={null}
INSERT INTO users (name, country, platform)
SELECT
    first_names[first_idx] || ' ' || last_names[last_idx] AS name,
    CASE
        WHEN random() < 0.25 THEN 'India'
        WHEN random() < 0.5 THEN 'USA'
        WHEN random() < 0.7 THEN 'Germany'
        WHEN random() < 0.85 THEN 'China'
        ELSE 'Other'
    END AS country,
    CASE
        WHEN random() < 0.2 THEN 'iOS'
        WHEN random() < 0.4 THEN 'Android'
        WHEN random() < 0.6 THEN 'Web'
        WHEN random() < 0.75 THEN 'Windows'
        WHEN random() < 0.9 THEN 'MacOS'
        ELSE 'Linux'
    END AS platform
FROM
    generate_series(1, 1000) AS seq
    CROSS JOIN LATERAL (
        SELECT
            array['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank', 'Grace', 'Hank', 'Ivy', 'Jack', 'Liam', 'Olivia', 'Noah', 'Emma', 'Sophia', 'Benjamin', 'Isabella', 'Lucas', 'Mia', 'Amelia', 'Aarav', 'Riya', 'Arjun', 'Ananya', 'Wei', 'Li', 'Huan', 'Mei', 'Hans', 'Klaus', 'Greta', 'Sofia'] AS first_names,
            array['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia', 'Miller', 'Davis', 'Martinez', 'Taylor', 'Anderson', 'Thomas', 'Jackson', 'White', 'Harris', 'Martin', 'Thompson', 'Moore', 'Lee', 'Perez', 'Sharma', 'Patel', 'Gupta', 'Reddy', 'Zhang', 'Wang', 'Chen', 'Liu', 'Schmidt', 'Müller', 'Weber', 'Fischer'] AS last_names,
            1 + (seq % 32) AS first_idx,
            1 + ((seq / 32)::int % 32) AS last_idx
    ) AS names;
```

<div id="run-queries">
  ### 查询你的数据
</div>

现在我们来运行一些查询，看看在使用 NVMe 存储时 Postgres 的响应速度有多快。

**按类型聚合 100 万条事件：**

```sql theme={null}
SELECT event_type, COUNT(*) as count 
FROM events 
GROUP BY event_type 
ORDER BY count DESC;
```

```text theme={null}
 event_type | count  
------------+--------
 click      | 499523
 view       | 375644
 purchase   | 112473
 signup     |  12117
 logout     |    243
(5 行)

时间: 114.883 ms
```

**结合 JSONB 过滤和日期范围进行查询：**

```sql theme={null}
SELECT COUNT(*) 
FROM events 
WHERE event_timestamp > NOW() - INTERVAL '30 days'
  AND event_data->>'additional_info' LIKE 'info_5%';
```

```text theme={null}
 count 
-------
  9042
(1 row)

Time: 109.294 ms
```

**将事件与用户联接：**

```sql theme={null}
SELECT u.country, COUNT(*) as events, AVG(LENGTH(e.event_data::text))::int as avg_json_size
FROM events e
JOIN users u ON e.user_id = u.user_id
GROUP BY u.country
ORDER BY events DESC;
```

```text theme={null}
 country | events | avg_json_size 
---------+--------+---------------
 USA     | 383748 |            52
 India   | 255990 |            52
 Germany | 223781 |            52
 China   | 127754 |            52
 Other   |   8727 |            52
(5 rows)

Time: 224.670 ms
```

<Info>
  **您的 Postgres 已准备就绪**

  至此，您已经拥有一个功能完善、性能出色的 Postgres 数据库，可用于承载事务型工作负载。

  继续阅读第 2 部分，了解原生 ClickHouse 集成如何显著提升您的分析能力。
</Info>

***

<div id="part-2">
  ## 第 2 部分：使用 ClickHouse 增加实时分析能力
</div>

虽然 Postgres 擅长事务处理工作负载 (OLTP) ，但 ClickHouse 是专为海量数据集上的分析查询 (OLAP) 而设计的。将两者集成后，你就能兼得两者之长：

* **Postgres** 用于应用程序的事务型数据 (插入、更新、按键查询)
* **ClickHouse** 用于对数十亿行数据进行亚秒级分析

本节将介绍如何将 Postgres 中的数据复制到 ClickHouse，并对其进行无缝查询。

<div id="setup-integrate-clickhouse">
  ### 设置 ClickHouse 集成
</div>

现在我们已经在 Postgres 中创建了表并写入了数据，接下来将这些表复制到 ClickHouse 中用于分析。首先，点击侧边栏中的 **ClickHouse 集成**。然后点击 **在 ClickHouse 中复制数据**。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/integration-landing.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=64b75fba8e85712c81f3e8fe42da9c4a" alt="Managed Postgres 集成为空" size="md" border width="3448" height="1982" data-path="images/managed-postgres/integration-landing.png" />

在接下来的表单中，你可以为集成输入一个名称，并选择一个现有的 ClickHouse 实例作为复制目标。如果你还没有 ClickHouse 实例，也可以直接在此表单中创建一个。

<Info>
  **重要**

  请确保所选的 ClickHouse 服务处于 Running 状态后再继续。
</Info>

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/postgres-analytics-form.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=c94299600b53d3e1b8d440bbd2c1dfa0" alt="Managed Postgres 集成表单" size="md" border width="3400" height="1976" data-path="images/managed-postgres/postgres-analytics-form.png" />

点击 **Next**，进入表选择器页面。在这里，你只需要：

* 选择一个要复制到的 ClickHouse database。
* 展开 **public** schema，并选择我们之前创建的 users 和 events 表。
* 点击 **将数据复制到 ClickHouse**。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/table-picker.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=35c4672a01c27232d5475a40c3bb8d21" alt="Managed Postgres 表选择器" size="md" border width="3400" height="1976" data-path="images/managed-postgres/table-picker.png" />

复制过程将会开始，随后你会进入集成概览页面。由于这是第一个集成，设置初始基础设施可能需要 2 到 3 分钟。在此期间，我们来看看新的 **pg\_clickhouse** extension。

<div id="pg-clickhouse-extension">
  ### 在 Postgres 中查询 ClickHouse
</div>

`pg_clickhouse` 扩展允许你使用标准 SQL 直接从 Postgres 查询 ClickHouse 中的数据。这意味着你的应用程序可以将 Postgres 作为统一的查询层，同时查询事务型和分析型数据。详情请参阅[完整文档](/zh/integrations/connectors/tools/pg_clickhouse/introduction)。

启用该扩展：

```sql theme={null}
CREATE EXTENSION pg_clickhouse;
```

然后，创建一个连接到 ClickHouse 的 foreign server。对于安全连接，请使用端口 `8443` 的 `http` 驱动：

```sql theme={null}
CREATE SERVER ch FOREIGN DATA WRAPPER clickhouse_fdw
       OPTIONS(driver 'http', host '<clickhouse_cloud_host>', dbname '<database_name>', port '8443');
```

将 `<clickhouse_cloud_host>` 替换为你的 ClickHouse 主机名，将 `<database_name>` 替换为你在设置复制时选择的数据库。你可以在 ClickHouse 服务中点击侧边栏里的 **Connect** 来找到主机名。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/get-clickhouse-host.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=3003f8d869f30ae992cff0329171ead2" alt="获取 ClickHouse 主机名" size="md" border width="695" height="765" data-path="images/managed-postgres/get-clickhouse-host.png" />

现在，将 Postgres 用户映射到 ClickHouse 服务的凭据：

```sql theme={null}
CREATE USER MAPPING FOR CURRENT_USER SERVER ch 
OPTIONS (user 'default', password '<clickhouse_password>');
```

现在将 ClickHouse 表导入 Postgres schema：

```sql theme={null}
CREATE SCHEMA organization;
IMPORT FOREIGN SCHEMA "<database_name>" FROM SERVER ch INTO organization;
```

将 `<database_name>` 替换为你在创建服务器时使用的数据库名称。

现在，你可以在 Postgres 客户端中看到所有 ClickHouse 表：

```sql theme={null}
\det+ organization.*
```

<div id="analytics-after-integration">
  ### 查看分析效果
</div>

让我们回到集成页面。你应该会看到初始复制已经完成。点击集成名称即可查看详细信息。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/EM4S4IbPPiA-8L1e/images/managed-postgres/analytics-list.png?fit=max&auto=format&n=EM4S4IbPPiA-8L1e&q=85&s=8cfd6695c4937c4ee5ff1cade83fc411" alt="Managed Postgres 分析列表" size="md" border width="1821" height="319" data-path="images/managed-postgres/analytics-list.png" />

点击服务名称，打开 ClickHouse Console 并查看你的复制表。

<Image img="https://mintcdn.com/private-7c7dfe99-mintlify-8a08bda2/1Ag2q2dX2WMxuS9G/images/managed-postgres/replicated-tables.png?fit=max&auto=format&n=1Ag2q2dX2WMxuS9G&q=85&s=4c412a71bdbac1081b7c12936818b25b" alt="ClickHouse 中的 Managed Postgres 复制表" size="md" border width="1725" height="1179" data-path="images/managed-postgres/replicated-tables.png" />

<div id="performance-comparison">
  ### 比较 Postgres 与 ClickHouse 的性能
</div>

现在我们来运行一些分析查询，对比 Postgres 和 ClickHouse 的性能。请注意，复制表采用 `public_<table_name>` 的命名约定。

**查询 1：按活跃度排序的高活跃用户**

此查询通过多个聚合找出最活跃的用户：

```sql theme={null}
-- 通过 ClickHouse
SELECT 
    user_id,
    COUNT(*) as total_events,
    COUNT(DISTINCT event_type) as unique_event_types,
    SUM(CASE WHEN event_type = 'purchase' THEN 1 ELSE 0 END) as purchases,
    MIN(event_timestamp) as first_event,
    MAX(event_timestamp) as last_event
FROM organization.public_events
GROUP BY user_id
ORDER BY total_events DESC
LIMIT 10;
```

```text theme={null}
 user_id | total_events | unique_event_types | purchases |        first_event         |         last_event         
---------+--------------+--------------------+-----------+----------------------------+----------------------------
       1 |        31439 |                  5 |      3551 | 2025-01-22 22:40:45.612281 | 2026-01-21 22:40:45.612281
       2 |        13235 |                  4 |      1492 | 2025-01-22 22:40:45.612281 | 2026-01-21 22:40:45.612281
...
(10 rows)

Time: 163.898 ms   -- ClickHouse
Time: 554.621 ms   -- 同一查询在 Postgres 上的耗时
```

**查询 2：按国家和平台划分的用户参与度**

此查询将 events 与 users 两张表关联，并计算参与度指标：

```sql theme={null}
-- 通过 ClickHouse
SELECT 
    u.country,
    u.platform,
    COUNT(DISTINCT e.user_id) as users,
    COUNT(*) as total_events,
    ROUND(COUNT(*)::numeric / COUNT(DISTINCT e.user_id), 2) as events_per_user,
    SUM(CASE WHEN e.event_type = 'purchase' THEN 1 ELSE 0 END) as purchases
FROM organization.public_events e
JOIN organization.public_users u ON e.user_id = u.user_id
GROUP BY u.country, u.platform
ORDER BY total_events DESC
LIMIT 10;
```

```text theme={null}
 country | platform | users | total_events | events_per_user | purchases 
---------+----------+-------+--------------+-----------------+-----------
 USA     | Android  |   115 |       109977 |             956 |     12388
 USA     | Web      |   108 |       105057 |             972 |     11847
 USA     | iOS      |    83 |        84594 |            1019 |      9565
 Germany | Android  |    85 |        77966 |             917 |      8852
 India   | Android  |    80 |        68095 |             851 |      7724
...
(10 rows)

Time: 170.353 ms   -- ClickHouse
Time: 1245.560 ms  -- 同一查询在 Postgres 上的耗时
```

**性能对比：**

| 查询                | Postgres (NVMe) | ClickHouse (通过 pg\_clickhouse) | 提速   |
| ----------------- | --------------- | ------------------------------ | ---- |
| 活跃用户 (5 个聚合)      | 555 ms          | 164 ms                         | 3.4x |
| 用户参与度 (JOIN + 聚合) | 1,246 ms        | 170 ms                         | 7.3x |

<Tip>
  **何时使用 ClickHouse**

  即使是在这个包含 100 万行的数据集上，ClickHouse 在包含 JOIN 和多个聚合的复杂分析查询中，性能也可提升 3–7 倍。随着规模进一步扩大 (超过 1 亿行) ，这种差距会更加明显：ClickHouse 的列式存储和向量化执行可带来 10–100 倍的加速。

  查询时间会因实例大小、服务间的网络延迟、数据特征以及当前负载而有所不同。
</Tip>

<div id="cleanup">
  ## 清理
</div>

要删除在本快速入门中创建的资源：

1. 首先，从 ClickHouse 服务中删除 ClickPipe 集成
2. 然后，在 Cloud Console 中删除 Managed Postgres 实例
