# 以 TiDB 作为数据操作数据层

## 概述

在本实验中，你将设置一个从 MySQL 源到 TiDB 目标的数据库复制任务。当 MySQL 发生数据变化时，你还将在 TiDB 上进行实时分析。如此一来，TiDB 作为操作数据层来平衡交易和分析的负载。

  ![60%](https://lab-static.pingcap.com/quick-demo/demo_012_en.png)

### 实验时长

+ 完成此练习大约需要 90 分钟。
 
### 任务

+ 为 TiDB 集群部署并启动 `TiDB Data Migration` 服务。
+ 启动从 MySQL 到 TiDB 的复制。
+ 在 MySQL 上进行数据更改，并在 TiDB 上进行实时分析。

> [!TIP]
> 点击 **开始** 启动实验环境。
> 环境准备就绪后，点击底部工具栏中的 **前进** 进入 **模块 1**。
> 然后，按照实验指南的步骤连接到实践环境并开始你的任务。

## 模块 1：连接到 MySQL Server 并运行查询以查看数据

### 步骤 1. 连接到远程 Linux

+ 点击这里 - [终端 1](ssh://monitor1-ssh#1) 打开一个新的终端，连接到为你的实践实验分配的虚拟机。

+ 登录后显示的横幅：

    ```output
     ,     #_
    ~\_  ####_        Amazon Linux 2
    ~~  \_#####\
    ~~     \###|      
    ~~       \#/ ___
    ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
     ~~._.   _/
        _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
      _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
    ```

### 步骤 2. 连接到 MySQL server 节点

+ 从远程 Linux 连接到 MySQL server 节点，如果有提示，回答 `yes`。

   ```bash
   ssh -i /home/ec2-user/.ssh/pe-class-key-oregon.pem rocky@${HOST_MYSQL1_PRIVATE_IP}
   ```
   ```output
   Last login: Wed Oct  9 02:16:14 2024 from 10.90.4.225
   [rocky@ip-10-90-1-132 ~]$
   ```

### 步骤 3. 以数据库用户 `root` 连接到 MySQL server

   ```bash
   mysql -h localhost -P 3306 -u root -pq1w2e3R4_ --connect-expired-password
   ```
   ```output
   mysql> 
   ```

### 步骤 4. 检查现有数据

+ 验证 `sbtest` 数据库中的表和数据已存在。
   
   ```sql
   SHOW DATABASES;
   ```
   ```output
   +--------------------+
   | Database           |
   +--------------------+
   | information_schema |
   | mysql              |
   | performance_schema |
   | sbtest             |
   | sp500insight       |
   | sys                |
   +--------------------+
   6 rows in set (0.00 sec)
   ```
   ```sql
   SHOW TABLES FROM sp500insight;
   ```
   ```output
   +------------------------+
   | Tables_in_sp500insight |
   +------------------------+
   | companies              |
   | index_compositions     |
   | index_price_history    |
   | indexes                |
   | stock_price_history    |
   | user_selected_stocks   |
   | users                  |
   +------------------------+
   7 rows in set (0.00 sec)
   ```

+ 查看 MySQL server 上 `sp500insight.stock_price_history` 表的行数。首次执行查询耗时超过 5 秒。

   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157000 |
   +----------+
   1 row in set (7.82 sec)
   ```
    
+ 退出到 MySQL server 节点。
   
   ```sql
   EXIT
   ```
   ```output
   bye
   [rocky@ip-10-90-1-132 ~]$
   ```

+ 保持终端与 MySQL 服务器的连接（你看到的提示符应以 `[rocky@`），然后继续下一个练习。

## 模块 2：将示例数据库从 MySQL 迁移并复制到 TiDB

### 步骤 1. 在 MySQL 中创建用于迁移的用户

+ 在[终端 1](ssh://monitor1-ssh#1) 上，连接到 MySQL server，创建一个专门用于迁移和复制的用户`dm_user`。

   ```bash
   X=q1w2e3R4_
   mysql -h localhost -P 3306 -uroot -p$X --connect-expired-password << EOF
   DROP USER IF EXISTS dm_user@'%';
   CREATE USER dm_user@'%' IDENTIFIED BY 'q1w2e3R4_';
   GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
   EXIT
   EOF
   ```
   ```output
   mysql: [Warning] Using a password on the command line interface can be insecure.
   ```

+ 退出到远程 TiUP 控制机。

   ```bash
   exit
   ```
   ```output
   logout
   Connection to 10.90.1.132 closed.
   ```

### 步骤 2. 验证 TiDB 集群已启动并正在运行

+ 检查 TiDB 集群状态。请注意，TiDB 集群 `tidb-demo` 中应该有 1 个 TiDB server，3 个 TiKV serverse 和 1 个 TiFlash server。
 
   ```bash
   ~/.tiup/bin/tiup cluster display tidb-demo
   ```
   ```output
   Cluster type:       tidb
   Cluster name:       tidb-demo
   Cluster version:    v8.1.0
   Deploy user:        ec2-user
   SSH type:           builtin
   Dashboard URL:      http://54.218.160.235:2379/dashboard
   Grafana URL:        http://10.90.4.225:3000
   ID                 Role          Host         Ports                            OS/Arch       Status  Data Dir                      Deploy Dir
   --                 ----          ----         -----                            -------       ------  --------                      ----------
   10.90.4.225:9093   alertmanager  10.90.4.225  9093/9094                        linux/x86_64  Up      /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
   10.90.4.225:3000   grafana       10.90.4.225  3000                             linux/x86_64  Up      -                             /tidb-deploy/grafana-3000
   10.90.3.54:2379    pd            10.90.3.54   2379/2380                        linux/x86_64  Up|L    /tidb-data/pd-2379            /tidb-deploy/pd-2379
   10.90.4.225:9090   prometheus    10.90.4.225  9090/12020                       linux/x86_64  Up      /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
   10.90.2.134:4000   tidb          10.90.2.134  4000/10080                       linux/x86_64  Up      -                             /tidb-deploy/tidb-4000
   10.90.4.150:9000   tiflash       10.90.4.150  9000/8123/3930/20170/20292/8234  linux/x86_64  Up      /tidb-data/tiflash-9000       /tidb-deploy/tiflash-9000
   10.90.1.183:20160  tikv          10.90.1.183  20160/20180                      linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   10.90.1.251:20160  tikv          10.90.1.251  20160/20180                      linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   10.90.1.41:20160   tikv          10.90.1.41   20160/20180                      linux/x86_64  Up      /tidb-data/tikv-20160         /tidb-deploy/tikv-20160
   Total nodes: 9
   ```

### 步骤 3. 在 TiDB 中创建用于迁移的用户

+ 在 TiDB 上创建一个专门用于迁移和复制的用户 `dm_user`。
   
   ```bash
   mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -uroot << 'EOF'
   DROP USER IF EXISTS dm_user@'%';
   CREATE USER dm_user@'%' identified by 'q1w2e3R4_';
   GRANT ALL PRIVILEGES ON *.* TO dm_user@'%';
   EXIT
   EOF
   ```

### 步骤 4. 在 TiDB 中创建目标数据库

+ 在 TiDB 中创建目标数据库 `sp500insight` 及其空表。这些表包括 `companies`, `index_compositions`, `index_price_history`, `indexes`, `stock_price_history`, `user_selected_stocks` 和 `users`。
   
   ```bash
   mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -uroot
   ```
   ```sql
   CREATE DATABASE sp500insight;
   USE sp500insight;
   CREATE TABLE `companies` (
     `stock_symbol` varchar(10) NOT NULL,
     `exchange_symbol` varchar(50) NOT NULL,
     `short_name` varchar(50) DEFAULT NULL,
     `long_name` varchar(100) DEFAULT NULL,
     `sector` varchar(50) DEFAULT NULL,
     `industry` varchar(50) DEFAULT NULL,
     `current_price` decimal(18,2) DEFAULT NULL,
     `market_cap` bigint(20) DEFAULT NULL,
     `ebitda` bigint(20) DEFAULT NULL,
     `revenue_growth` float DEFAULT NULL,
     `city` varchar(50) DEFAULT NULL,
     `state` varchar(50) DEFAULT NULL,
     `country` varchar(50) DEFAULT NULL,
     `country_code` varchar(3) DEFAULT NULL,
     `full_time_employees` int(11) DEFAULT NULL,
     `long_business_summary` text DEFAULT NULL,
     PRIMARY KEY (stock_symbol, exchange_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `index_compositions` (
     `index_symbol` varchar(10) DEFAULT NULL,
     `stock_symbol` varchar(10) NOT NULL,
     `weight` double DEFAULT NULL,
     PRIMARY KEY (stock_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `index_price_history` (
     `record_date` date NOT NULL,
     `index_symbol` varchar(10) NOT NULL,
     `price` decimal(18,2) DEFAULT NULL,
     PRIMARY KEY (record_date, index_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `indexes` (
     `index_symbol` varchar(10) NOT NULL,
     `short_name` varchar(50) DEFAULT NULL,
     PRIMARY KEY (index_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `stock_price_history` (
     `record_date` date NOT NULL,
     `stock_symbol` varchar(10) NOT NULL,
     `adj_close` decimal(32,16) DEFAULT NULL,
     `close` decimal(32,16) DEFAULT NULL,
     `high` decimal(32,16) DEFAULT NULL,
     `low` decimal(32,16) DEFAULT NULL,
     `open` decimal(32,16) DEFAULT NULL,
     `volume` bigint(20) DEFAULT NULL,
     PRIMARY KEY (record_date, stock_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `user_selected_stocks` (
     `user_id` int(11) NOT NULL,
     `stock_symbol` varchar(10) NOT NULL,
     `created_date` datetime DEFAULT NULL,
     PRIMARY KEY (user_id, stock_symbol)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   CREATE TABLE `users` (
     `user_id` int(11) NOT NULL,
     `created_date` datetime DEFAULT NULL,
     PRIMARY KEY (user_id)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
   SET GLOBAL allow_auto_random_explicit_insert = true;
   ```

### 步骤 5. 为分析查询启用 TiFlash

+ 为  `sp500insight.stock_price_history` 表启用 TiFlash 分析列式存储。
   
   ```sql
   ALTER TABLE sp500insight.stock_price_history SET TIFLASH REPLICA 1;
   EXIT;
   ```
   ```output
   Query OK, 0 rows affected (0.10 sec)
   Bye
   ```

### 步骤 6. 安装 TiDB Data Migration 工具

+ 安装 TiDB Data Migration 组件。
   
   ```bash
   ~/.tiup/bin/tiup install dm dmctl:vtidb_version dm-master:vtidb_version dm-worker:vtidb_version
   ```
   ```bash
   ~/.tiup/bin/tiup list --verbose | grep dm
   ```
   ```output
   dm                 pingcap  v1.15.1,v1.16.0                     linux/amd64  Data Migration Platform manager
   dm-master          pingcap  v8.0.0,vtidb_version                       linux/amd64  dm-master component of Data Migration Platform.
   dm-worker          pingcap  v8.0.0,vtidb_version                       linux/amd64  dm-worker component of Data Migration Platform.
   dmctl              pingcap  v6.5.1,v6.5.9,v7.5.0,vtidb_version  linux/amd64  dmctl component of Data Migration Platform.
   ```

### 步骤 7. 查看 TiDB Data Migration 集群拓扑文件

+ TiDB Data Migration 集群拓扑配置文件已为你预配置好。请查看配置，无需更改。

   ```bash
   cat dm-topology.yaml 
   ```
   ```output
   global:
     user: "ec2-user"
     ssh_port: 22
     deploy_dir: "/tidb-deploy"
     data_dir: "/tidb-data"
     arch: "amd64"
   master_servers:
     - host: 10.90.4.225
   worker_servers:
     - host: 10.90.4.225
   monitoring_servers:
     - host: 10.90.3.54
   grafana_servers:
     - host: 10.90.3.54
   alertmanager_servers:
     - host: 10.90.3.54
   ```

### 步骤 8. 部署并启动 TiDB Data Migration 集群

+ 部署 TiDB Data Migration 集群 - `dm-test`

   ```bash
   ~/.tiup/bin/tiup dm deploy dm-test vtidb_version ./dm-topology.yaml \
    --user ec2-user \
    -i /home/ec2-user/.ssh/pe-class-key-oregon.pem \
    --yes
   ```
   ```output
   Starting component dm: /home/ec2-user/.tiup/components/dm/v1.16.0/tiup-dm deploy dm-test vtidb_version ./dm-topology.yaml --user ec2-user -i /home/ec2-user/.ssh/pe-class-key-oregon.pem --yes
   + Detect CPU Arch Name
   .
   .
   .
   Cluster `dm-test` deployed successfully, you can start it with command: `tiup dm start dm-test`
   ```

+ 启动 TiDB Data Migration 集群 - `dm-test`.

   ```bash
   ~/.tiup/bin/tiup dm start dm-test
   ```
   ```output
   Starting component dm: /home/ec2-user/.tiup/components/dm/v1.16.0/tiup-dm start dm-test
   Starting cluster dm-test...
   + [ Serial ] - SSHKeySet: privateKey=/home/ec2-user/.tiup/storage/dm/clusters/dm-test/ssh/id_rsa, publicKey=/home/ec2-user/.tiup/storage/dm/clusters/dm-test/ssh/id_rsa.pub
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.1.7
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.3.71
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.1.7
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.4.191
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.1.7
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.3.49
   + [Parallel] - UserSSH: user=ec2-user, host=10.90.3.135
   + [ Serial ] - StartCluster
   Starting component dm-master
   	Starting instance 10.90.4.191:8261
   	Start instance 10.90.4.191:8261 success
   Starting component dm-worker
   	Starting instance 10.90.3.135:8262
   	Starting instance 10.90.3.49:8262
   	Starting instance 10.90.3.71:8262
   	Start instance 10.90.3.135:8262 success
   	Start instance 10.90.3.71:8262 success
   	Start instance 10.90.3.49:8262 success
   Starting component prometheus
   	Starting instance 10.90.1.7:9090
   	Start instance 10.90.1.7:9090 success
   Starting component grafana
   	Starting instance 10.90.1.7:3000
   	Start instance 10.90.1.7:3000 success
   Starting component alertmanager
   	Starting instance 10.90.1.7:9093
   	Start instance 10.90.1.7:9093 success
   Started cluster `dm-test` successfully
   ```
  
+ 确认 TiDB Data Migration 集群已启动并正在运行。

   ```bash
   tiup dm display dm-test
   ```
   ```output
   Starting component dm: /home/ec2-user/.tiup/components/dm/v1.16.0/tiup-dm display dm-test
   Cluster type:       dm
   Cluster name:       dm-test
   Cluster version:    vtidb_version
   Deploy user:        ec2-user
   SSH type:           builtin
   Grafana URL:        http://10.90.3.188:3000
   ID                Role          Host         Ports      OS/Arch       Status     Data Dir                      Deploy Dir
   --                ----          ----         -----      -------       ------     --------                      ----------
   10.90.3.188:9093  alertmanager  10.90.3.188  9093/9094  linux/x86_64  Up         /tidb-data/alertmanager-9093  /tidb-deploy/alertmanager-9093
   10.90.4.196:8261  dm-master     10.90.4.196  8261/8291  linux/x86_64  Healthy|L  /tidb-data/dm-master-8261     /tidb-deploy/dm-master-8261
   10.90.4.196:8262  dm-worker     10.90.4.196  8262       linux/x86_64  Free       /tidb-data/dm-worker-8262     /tidb-deploy/dm-worker-8262
   10.90.3.188:3000  grafana       10.90.3.188  3000       linux/x86_64  Up         -                             /tidb-deploy/grafana-3000
   10.90.3.188:9090  prometheus    10.90.3.188  9090       linux/x86_64  Up         /tidb-data/prometheus-9090    /tidb-deploy/prometheus-9090
   Total nodes: 5
   ``` 

### 步骤 9. 配置迁移源

+ 设置迁移任务源配置。

   ```bash
   cat << EOF > mysql-source-conf1.yaml
   source-id: "mysql-replica-01"
   from:
     host: "${HOST_MYSQL1_PRIVATE_IP}"
     port: 3306
     user: "dm_user"
     password: "q1w2e3R4_"
   EOF
   cat mysql-source-conf1.yaml
   ```
   ```output
   source-id: "mysql-replica-01"
   from:
     host: "10.90.1.135"
     port: 3306
     user: "dm_user"
     password: "q1w2e3R4_"
   ```

+ 将 MySQL 实例设置为迁移源，并验证 TiDB 数据迁移集群能够识别该源。  
   
   ```bash
   ~/.tiup/bin/tiup dmctl:vtidb_version \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 operate-source create mysql-source-conf1.yaml
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/vtidb_version/dmctl/dmctl --master-addr=10.90.4.66:8261 operate-source create mysql-source-conf1.yaml
   {
       "result": true,
       "msg": "",
       "sources": [
           {
               "result": true,
               "msg": "",
               "source": "mysql-replica-01",
               "worker": "dm-10.90.3.187-8262"
           }
       ]
   }
   ```
   ```bash
   ~/.tiup/bin/tiup dmctl:vtidb_version \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 get-config source mysql-replica-01
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/vtidb_version/dmctl/dmctl --master-addr=10.90.4.66:8261 get-config source mysql-replica-01
   {
       "result": true,
       "msg": "",
       "cfg": "enable: true\nenable-gtid: false\nauto-fix-gtid: false\nrelay-dir: relay-dir\nmeta-dir: \"\"\nflavor: mysql\ncharset: \"\"\nenable-relay: false\nrelay-binlog-name: \"\"\nrelay-binlog-gtid: \"\"\nsource-id: mysql-replica-01\nfrom:\n  host: 10.90.1.135\n  port: 3306\n  user: dm_user\n  password: '******'\n  max-allowed-packet: null\n  session: {}\n  security: null\npurge:\n  interval: 3600\n  expires: 0\n  remain-space: 15\nchecker:\n  check-enable: true\n  backoff-rollback: 5m0s\n  backoff-max: 5m0s\n  check-interval: 5s\n  backoff-min: 1s\n  backoff-jitter: true\n  backoff-factor: 2\nserver-id: 429530419\ntracer: {}\ncase-sensitive: false\nfilters: []\n"
   }
   ```
   ```bash
   ~/.tiup/bin/tiup dmctl:vtidb_version \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 operate-source show
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/vtidb_version/dmctl/dmctl --master-addr=10.90.4.66:8261 operate-source show
   {
       "result": true,
       "msg": "",
       "sources": [
           {
               "result": true,
               "msg": "",
               "source": "mysql-replica-01",
               "worker": "dm-10.90.3.187-8262"
           }
       ]
   }
   ```

### 步骤 10. 创建并启动迁移任务

+ 创建迁移任务配置并启动迁移任务。该任务将持续把 `sp500insight` 数据库的更改从 MySQL server 迁移并复制到 TiDB 集群。

+ 生成迁移任务配置。

   ```bash
   cat << EOF > dm-task.yaml
   name: "dm-task"
   task-mode: all
   ignore-checking-items: ["auto_increment_ID"]

   target-database:
     host: "${HOST_DB1_PRIVATE_IP}"
     port: 4000
     user: "dm_user"
     password: "q1w2e3R4_"

   mysql-instances:
     - source-id: "mysql-replica-01"
       route-rules: ["instance-1-user-schema-rule"]
       block-allow-list: "rule_1"
       mydumper-config-name: "global"
       loader-config-name: "global"

   routes:
     instance-1-user-schema-rule:
       schema-pattern: "sp500insight"
       target-schema: "sp500insight"

   block-allow-list:
     rule_1:
       do-dbs: ["sp500insight"]

   mydumpers:
     global:
       threads: 32
       chunk-filesize: 64

   loaders:
     global:
       pool-size: 8
       import-mode: "physical"
       pd-addr: "${HOST_PD1_PRIVATE_IP}:2379"
   EOF
   cat dm-task.yaml
   ```
    ```output
    name: "dm-task"
    task-mode: all
    ignore-checking-items: ["auto_increment_ID"]
    .
    .
    .
    loaders:
      global:
        pool-size: 32
        import-mode: "physical"
    ```

+ 预检查迁移任务。msg 应显示 `pre-check is passed`.

  ```bash
  ~/.tiup/bin/tiup dmctl:vtidb_version \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 check-task ./dm-task.yaml
  ```
  ```output
  Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/vtidb_version/dmctl/dmctl --master-addr=10.90.4.235:8261 check-task ./dm-task.yaml
  {
  "result": true,
  "msg": "pre-check is passed. "
  }
    ```

+ 启动迁移和复制任务，并检查迁移进度。
   
   ```bash
   ~/.tiup/bin/tiup dmctl:vtidb_version \
    --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 start-task ./dm-task.yaml
   ```
   ```output
   Starting component dmctl: /home/ec2-user/.tiup/components/dmctl/vtidb_version/dmctl/dmctl --master-addr=10.90.4.66:8261 start-task ./dm-task.yaml
   {
       "result": true,
       "msg": "",
       "sources": [
           {
               "result": true,
               "msg": "",
               "source": "mysql-replica-01",
               "worker": "dm-10.90.3.187-8262"
           }
       ],
       "checkResult": "pre-check is passed. "
   }
   ```

### 步骤 11. 检查迁移进度

+ 多次使用 `query-status` 操作检查迁移状态。注意 `subTaskStatus` 中的 `stage`, `unit` 和 `progress` 属性。该任务包含 3 个子任务单元：`Dump`, `Load` 和 `Sync`。

+ 使用 `watch` 命令监控整个任务的进度。阅读以下更多信息，并在屏幕上观察迁移进度。

   ```bash
   watch -n 1 -d ~/.tiup/bin/tiup dmctl:vtidb_version --master-addr=${HOST_MONITOR1_PRIVATE_IP}:8261 query-status ./dm-task.yaml
   ```
  
+ 单元 `Dump`, 阶段 `Running`:
   
    ```output
    {
    ...
          "subTaskStatus": [
              {
                  "name": "dm-task",
                  "stage": "Running",
                  "unit": "Dump",
                  "result": null,
                  "unresolvedDDLLockID": "",
                  "dump": {
                      "totalTables": "6",
                      "completedTables": 3,
                      "finishedBytes": 7949200595,
                      "finishedRows": 39359277,
                      "estimateTotalRows": 59224808,
                      "bps": "57472325",
                      "progress": "64.63 %"
                  },
                  "validation": null
              }
          ]
      }
    ]
    }
    ```

+ 单元 `Load`, 阶段 `Running`:

    ```output
    {
    ...
             "subTaskStatus": [
                 {
                     "name": "dm-task",
                     "stage": "Running",
                     "unit": "Load",
                     "result": null,
                     "unresolvedDDLLockID": "",
                     "load": {
                         "finishedBytes": "5307344924",
                         "totalBytes": "8161057816",
                         "progress": "65.03 %",
                         "metaBinlog": "(binlog.000008, 157240317)",
                         "metaBinlogGTID": "",
                         "bps": "62882221"
                     },
                     "validation": null
                 }
             ]
         }
     ]
    }
    ```

+ 单元 `Sync`, 阶段 `Running`. 请注意目标 TiDB 和源 MySQL 已同步。

    ```output
    {
    ...
                "subTaskStatus": [
                    {
                        "name": "dm-task",
                        "stage": "Running",
                        "unit": "Sync",
                        "result": null,
                        "unresolvedDDLLockID": "",
                        "sync": {
                            "totalEvents": "19767046",
                            "totalTps": "21118",
                            "recentTps": "0",
                            "masterBinlog": "(binlog.000011, 706201359)",
                            "masterBinlogGtid": "",
                            "syncerBinlog": "(binlog.000011, 706201359)",
                            "syncerBinlogGtid": "00000000-0000-0000-0000-000000000000:0",
                            "blockingDDLs": [
                            ],
                            "unresolvedGroups": [
                            ],
                            "synced": true,
                            "binlogType": "remote",
                            "secondsBehindMaster": "0",
                            "blockDDLOwner": "",
                            "conflictMsg": "",
                            "totalRows": "19767046",
                            "totalRps": "21118",
                            "recentRps": "0"
                        },
                        "validation": null
                    }
                ]
            }
        ]
    }
    ```

+等待并确认迁移和复制的 `subTaskStatus` 已达到 `"stage": "Running"` 和 `"unit": "Sync"` 状态。保持 `watch` 命令运行，然后继续下一个练习。

## 模块 3：在上游 MySQL 进行更改并在下游 TiDB 运行实时分析查询

### 步骤 1. 从远程 Linux 的 monitor1_address 连接到 TiDB server 实例

+ 点击这里 - [终端 2](ssh://monitor1-ssh#2) 打开一个新的终端，然后连接到 monitor1_address，接着连接到 TiDB 集群。

+ 登录后显示的横幅：

    ```output
     ,     #_
    ~\_  ####_        Amazon Linux 2
    ~~  \_#####\
    ~~     \###|      
    ~~       \#/ ___
    ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
     ~~._.   _/
        _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
      _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
    ```


+ 连接到 TiDB 集群。

   ```bash
   export MYSQL_PS1="tidb:db1> "
   mysql -h ${HOST_DB1_PRIVATE_IP} -P 4000 -u root
   ```
   ```output
   tidb:db1> 
   ```

### 步骤 2. 在下游 TiDB 运行查询

+ 查询 TiDB 上 `sp500insight.stock_price_history` 表的行数。首次执行查询耗时不到 0.1 秒。
   
   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157000 |
   +----------+
   1 row in set (0.03 sec)
   ```

### 步骤 3. 在上游 MySQL 运行 INSERT 操作

+ 点击这里 - [终端 3](ssh://monitor1-ssh#3) 打开一个新的终端，连接到 monitor1_address，然后连接到 MySQL server。

+ 登录后显示的横幅：

    ```output
     ,     #_
    ~\_  ####_        Amazon Linux 2
    ~~  \_#####\
    ~~     \###|      
    ~~       \#/ ___
    ~~       V~' '->
    ~~~         /    A newer version of Amazon Linux is available!
     ~~._.   _/
        _/ _/       Amazon Linux 2023, GA and supported until 2028-03-15.
      _/m/'           https://aws.amazon.com/linux/amazon-linux-2023/
    ```


+ 连接到 MySQL server 节点。

   ```bash
   ssh -i /home/ec2-user/.ssh/pe-class-key-oregon.pem rocky@${HOST_MYSQL1_PRIVATE_IP}
   ```
   ```output
   Last login: Thu Aug  1 11:58:47 2024 from 10.90.4.90
   [rocky@ip-10-90-1-235 ~]$
   ```

+ 通过数据库会话连接到 MySQL server。
   
   ```bash
   mysql -h localhost -P 3306 -u root -pq1w2e3R4_ --connect-expired-password
   ```
   ```output
   mysql> 
   ```

+ 在[终端 3](ssh://monitor1-ssh#3)（MySQL 端），向 `sp500insight.stock_price_history` 表中 `INSERT` a一行新数据。验证行数已从 `1157000` 增加到 `1157001`。
   
   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   INSERT INTO sp500insight.stock_price_history VALUES (
    '2020-01-12','MMM',60.3188858032226560,77.0199966430664000,67.4499969482421900,91.6699981689453100,91.0899963378906200,3043700);
   SELECT COUNT(*) FROM  sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157000 |
   +----------+
   1 row in set (0.17 sec)
   ...
   Query OK, 1 row affected (0.01 sec)
   ...
   +----------+
   | COUNT(*) |
   +----------+
   |  1157001 |
   +----------+
   1 row in set (0.17 sec)
   ```

### 步骤 4. 再次在下游 TiDB 运行查询以观察更改

+ 回到[终端 2](ssh://monitor1-ssh#2) （TiDB 端），观察来自 TiDB 端的更改结果，该更改已从 MySQL 同步过来。行数应为 `1157001`。
   
   ```sql
   SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +----------+
   | COUNT(*) |
   +----------+
   |  1157001 |
   +----------+
   1 row in set (0.04 sec)
   ```

### 步骤 5. 观察 TiDB 上的执行计划

+ 查看 TiDB 中之前 `COUNT()` 查询的执行计划。注意 `task` 列，其中 `mpp[tiflash]` 表示这些任务将在列式存储层 TiFlash 中利用大规模并行处理。
   
   ```bash
   EXPLAIN SELECT COUNT(*) FROM sp500insight.stock_price_history;
   ```
   ```output
   +------------------------------+------------+--------------+---------------------------+----------------------------------------------------------------------+
   | id                           | estRows    | task         | access object             | operator info                                                        |
   +------------------------------+------------+--------------+---------------------------+----------------------------------------------------------------------+
   | HashAgg_22                   | 1.00       | root         |                           | funcs:count(Column#11)->Column#9                                     |
   | └─TableReader_24             | 1.00       | root         |                           | MppVersion: 2, data:ExchangeSender_23                                |
   |   └─ExchangeSender_23        | 1.00       | mpp[tiflash] |                           | ExchangeType: PassThrough                                            |
   |     └─HashAgg_9              | 1.00       | mpp[tiflash] |                           | funcs:count(sp500insight.stock_price_history.record_date)->Column#11 |
   |       └─TableFullScan_21     | 1157000.00 | mpp[tiflash] | table:stock_price_history | keep order:false                                                     |
   +------------------------------+------------+--------------+---------------------------+----------------------------------------------------------------------+
   ```

+ 如果时间允许，在 MySQL 端进行更多修改实验，并观察 TiDB 中的结果，以及在 TiDB 中执行其他分析查询。例如：
   ```sql
   USE sp500insight;
   WITH index_companies AS (
      SELECT
          c.stock_symbol, c.short_name, c.exchange_symbol, ic.weight, c.market_cap AS market_cap, c.revenue_growth AS revenue_growth
      FROM companies c
      JOIN index_compositions ic ON c.stock_symbol = ic.stock_symbol
      WHERE index_symbol = 'SP500' AND sector = 'Energy'
   ), companies_latest_price AS (
      SELECT
          stock_symbol, DATE(last_day) AS last_change_day, last_close_price, last_2nd_close_price, 
          last_close_price - last_2nd_close_price AS last_change,
          (last_close_price - last_2nd_close_price) / last_2nd_close_price AS last_change_percentage
      FROM (
        SELECT
          LAST_VALUE(stock_symbol) OVER (PARTITION BY stock_symbol ORDER BY record_date) AS stock_symbol,
          LAST_VALUE(record_date) OVER (PARTITION BY stock_symbol ORDER BY record_date) AS last_day,
          NTH_VALUE(close, 1) OVER (PARTITION BY stock_symbol ORDER BY record_date DESC) AS last_close_price,
          NTH_VALUE(close, 2) OVER (PARTITION BY stock_symbol ORDER BY record_date DESC) AS last_2nd_close_price,
          ROW_NUMBER() OVER (PARTITION BY stock_symbol ORDER BY record_date DESC) AS row_num
        FROM stock_price_history sph
        WHERE
          record_date > DATE_SUB((SELECT MAX(record_date) FROM stock_price_history), INTERVAL 2 DAY)
          AND sph.stock_symbol IN (SELECT stock_symbol FROM index_companies ic)
      ) sub
      WHERE
          row_num = 2
   )
   SELECT
      ic.stock_symbol, ic.exchange_symbol, ic.short_name, ic.weight, ic.market_cap, ic.revenue_growth,
      clp.last_change, clp.last_change_day, clp.last_close_price, clp.last_2nd_close_price, clp.last_change_percentage
   FROM index_companies ic
   LEFT JOIN companies_latest_price clp ON ic.stock_symbol = clp.stock_symbol
   ORDER BY ic.weight DESC;
   ```
   ```output
   +--------------+-----------------+---------------------------------+------------------------+--------------+----------------+---------------------+-----------------+----------------------+----------------------+-------------------------+
   | stock_symbol | exchange_symbol | short_name                      | weight                 | market_cap   | revenue_growth | last_change         | last_change_day | last_close_price     | last_2nd_close_price | last_change_percentage  |
   +--------------+-----------------+---------------------------------+------------------------+--------------+----------------+---------------------+-----------------+----------------------+----------------------+-------------------------+
   | XOM          | NYQ             | Exxon Mobil Corporation         |   0.013441937585551282 | 474511933440 |          0.689 |  1.2800064086914100 | 2023-01-10      | 111.3700027465820300 | 110.0899963378906200 |  0.01162690935843785832 |
   | CVX          | NYQ             | Chevron Corporation             |   0.009567226003564158 | 337731289088 |           0.81 | -0.8399963378906000 | 2023-01-10      | 175.1999969482422000 | 176.0399932861328000 | -0.00477162218772232275 |
   | COP          | NYQ             | ConocoPhillips                  |   0.004417814517419704 | 155952644096 |          1.237 |  0.1599960327148400 | 2023-01-10      | 118.2399978637695300 | 118.0800018310546900 |  0.00135497993084178221 |
   | SLB          | NYQ             | Schlumberger N.V.               |  0.0022377960040345308 |  78996119552 |          0.279 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | EOG          | NYQ             | EOG Resources, Inc.             |  0.0021024604924476343 |  74218659840 |          0.924 | -0.7600021362304600 | 2023-01-10      | 126.8499984741211000 | 127.6100006103515600 | -0.00595566282105957140 |
   | MPC          | NYQ             | Marathon Petroleum Corporation  |   0.002050747487098508 |  72393146368 |          0.818 |  1.0999984741211000 | 2023-01-10      | 117.5999984741211000 | 116.5000000000000000 |  0.00944204698816394850 |
   | OXY          | NYQ             | Occidental Petroleum Corporatio |   0.001695676548826279 |  59858837504 |          0.792 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | PXD          | NYQ             | Pioneer Natural Resources Compa |  0.0016017013932190817 |  56541433856 |          0.641 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | VLO          | NYQ             | Valero Energy Corporation       |  0.0015472850935959574 |  54620491776 |          0.593 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | HES          | NYQ             | Hess Corporation                |  0.0012744122628788822 |  44987846656 |          0.776 |  1.6300048828125000 | 2023-01-10      | 145.2500000000000000 | 143.6199951171875000 |  0.01134942861878312162 |
   | PSX          | NYQ             | Phillips 66                     |  0.0012589621320069535 |  44442443776 |          0.799 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | KMI          | NYQ             | Kinder Morgan, Inc.             |  0.0012062691273686955 |  42582335488 |          0.354 |  0.0400009155273440 | 2023-01-10      |  18.7800006866455080 |  18.7399997711181640 |  0.00213452059850037319 |
   | DVN          | NYQ             | Devon Energy Corporation        |  0.0012053375130788024 |  42549448704 |          0.789 | -0.2800025939941400 | 2023-01-10      |  62.8499984741210940 |  63.1300010681152340 | -0.00443533326875800678 |
   | WMB          | NYQ             | Williams Companies, Inc. (The)  |  0.0011162172177908748 |  39403425792 |          0.091 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | HAL          | NYQ             | Halliburton Company             |  0.0010393744130051477 |  36690808832 |          0.388 |  0.0500030517578160 | 2023-01-10      |  40.9900016784668000 |  40.9399986267089840 |  0.00122137404580161222 |
   | OKE          | NYQ             | ONEOK, Inc.                     |  0.0008854096904464799 |  31255721984 |          0.769 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | BKR          | NMS             | Baker Hughes Company            |  0.0008807471517968449 |  31091130368 |          0.054 | -0.0400009155273450 | 2023-01-10      |  30.8299999237060550 |  30.8700008392334000 | -0.00129578602008027511 |
   | FANG         | NMS             | Diamondback Energy, Inc.        |   0.000730020047064916 |  25770334208 |          0.565 |  0.2900085449218600 | 2023-01-10      | 142.2400054931640600 | 141.9499969482422000 |  0.00204303311839874783 |
   | MRO          | NYQ             | Marathon Oil Corporation        |  0.0005965698099807201 |  21059426304 |          0.731 |  0.0399990081787110 | 2023-01-10      |  27.0499992370605470 |  27.0100002288818360 |  0.00148089625471161593 |
   | CTRA         | NYQ             | Coterra Energy Inc.             |  0.0005690298110137097 |  20087240704 |          5.204 | -0.3899993896484380 | 2023-01-10      |  24.6900005340576170 |  25.0799999237060550 | -0.01555021494556719473 |
   | TRGP         | NYQ             | Targa Resources, Inc.           |  0.0004842024080652878 |  17092760576 |          0.773 |                NULL | NULL            |                 NULL |                 NULL |                    NULL |
   | APA          | NMS             | APA Corporation                 | 0.00039910236086756015 |  14088655872 |          0.374 |  0.5799980163574200 | 2023-01-10      |  43.8199996948242200 |  43.2400016784668000 |  0.01341345961709929139 |
   | EQT          | NYQ             | EQT Corporation                 |  0.0003576031445812937 |  12623697920 |          1.092 | -0.6399993896484380 | 2023-01-10      |  33.4000015258789060 |  34.0400009155273440 | -0.01880139166966068805 |
   +--------------+-----------------+---------------------------------+------------------------+--------------+----------------+---------------------+-----------------+----------------------+----------------------+-------------------------+
   23 rows in set (0.01 sec)
   ```

## 结论

### 发挥 TiDB 作为操作数据存储层的强大功能

TiDB 作为一款先进的分布式 SQL 数据库，正凭借其强大的架构，在操作数据存储（ODS）领域崭露头角。该架构支持混合事务分析处理（HTAP）工作负载，使其能胜任此角色。TiDB 设计为与 MySQL 兼容，具备高可用性、强一致性和水平扩展性，是动态且数据密集型应用的理想解决方案。
操作数据存储作为一个中央存储库，聚合来自各种数据源的数据，旨在促进实时数据分析和报告等操作。与传统数据仓库不同，ODS 通常实时更新，并充当主要操作系统和数据仓库之间的中间环节。

### 实时数据集成与混合工作负载

TTiDB 能够同时处理 OLTP 和 OLAP 工作负载，这一特性使其在操作数据存储领域独树一帜。这种混合能力确保企业能够在不影响事务处理性能的情况下，实时执行复杂的分析查询。 深入了解 TiDB 如何实现这种混合特性，请查看 [HTAP 深入探索指南](https://docs.pingcap.com/zh/tidb/v8.4/explore-htap).

使用 TiDB 作为 ODS 能够显著简化数据聚合流程。以一家零售公司为例，该公司需要整合来自销售点系统、库存数据库和客户服务日志的数据。借助 TiDB 的 HTAP 功能，公司可以实时分析销售趋势、库存水平和客户反馈，从而在无需传统批处理方法带来延迟的情况下，即时做出运营决策。

### 适合处理大量数据的架构

对于处理大量事务数据的企业而言，TiDB 能够在多个节点间自动复制数据，确保可用性和可靠性，让企业安心。多 raft 协议进一步保障了高可用性，即使部分基础设施出现故障，企业数据依然安全。

### 简化操作并降低复杂性

将 TiDB 部署为 ODS 可极大地简化技术堆栈。传统系统通常依赖多种不同工具进行数据摄取、ETL（提取、转换、加载）处理和存储，这不仅增加了维护复杂性，还提高了成本。TiDB 通过提供一个单一平台来处理完整的数据生命周期 —— 从捕获数据到查询数据，消除了这种复杂性。

例如，在金融领域，快速聚合和查询大量数据集对于合规性和市场分析至关重要，TiDB 可以取代复杂的 ETL 流程，直接摄取数据以进行即时分析。

TiDB 凭借其强大的 HTAP 功能、可扩展架构以及与现有系统的易集成性，在操作数据存储领域脱颖而出。通过利用这些优势，组织能够从数据中获取更多价值，实时做出更明智的决策，并轻松扩展以满足不断变化的业务需求。随着各行业日益数据驱动，选择像 TiDB 这样合适的技术对于保持竞争力和敏捷性至关重要。

若要进一步探索在组织架构中实施 TiDB 的更多内容，可深入了解 [TiDB Cloud platform](https://tidbcloud.com)，轻松开启利用分布式 SQL 强大功能的旅程，而无需承担过多运营负担。