---
title: "ざっくり TiDB 入門してみた | grasys blog"
url: "https://blog.grasys.io/post/arai/tidb-introduction"
description: "こんにちは、新井です。 直近の案件で TiDB を使用する可能性があり、どんな特徴の DB なのかざっくり調べてみました。 また mac 上でも簡単に動かしてみました。 TiDB とは TiDB は NewSQL に対応した MySQL 互換なハイブリットトランザクション / 分析処理（HTAP）ワークロードをサポー…"
---

# ざっくり TiDB 入門してみた

-   ![](/_astro/noicon.CTHOhNiB_1HMs6A.webp)[arai](/authors/arai/)
-   公開日：2024年10月9日
-   カテゴリー：[Tech](/categories/tech/)
-   タグ：[#TiDB](/tags/tidb/)

![ざっくり TiDB 入門してみた](/_astro/hero.BjRcjNYU_59gdS.webp)

こんにちは、新井です。

直近の案件で TiDB を使用する可能性があり、どんな特徴の DB なのかざっくり調べてみました。

また mac 上でも簡単に動かしてみました。

## TiDB とは

TiDB は NewSQL に対応した MySQL 互換なハイブリットトランザクション / 分析処理（HTAP）ワークロードをサポートする分散 SQL データベースです。

### NewSQL とは

リレーショナルデータベースのように SQL やトランザクションなどの機能を持ち、スケールアウト性も持ち合わせたデータベースを指します。

特徴として Reader だけではなく、Writer もスケールさせることができ、書き込みのスループットをあげることができます。

Google Spanner や CockroachDB などが有名です。

ハイブリットトランザクション / 分析処理（HTAP）とは

![ざっくり TiDB 入門してみたの画面（1）](/_astro/01-7693e3a01e418e7a0b2870a1135a2c73-c15beea3.CVAVwkKi_1rgGt.webp)

OLTP（オンライントランザクション処理）と OLAP（オンライン分析処理）の両方のワークロードを同時に処理できるハイブリッドデータベースのことです。

一般的に MySQL、PostgreSQL、SQL Server のようなリレーショナルデータベースは OLTP に優れたデータベースに分類されます。トランザクションを使用し、行単位での更新や削除処理を得意とする一方で、集計やソートなどは不得意です。

このような集計やソートなど OLAP に向いているのは BigQuery や Apache Cassandra などの列指向データベースです。

TiDB では RDB のような OLTP によるデータ更新や削除と、OLAP による集計やソートなどのデータ分析の両方を行えるデータベースになっています。

また TiDB は NewSQL と呼ばれるデータベースに分類されます。

## TiDB のアーキテクチャ

### コンポーネント

[![コンポーネントの画面](/_astro/02-f0a0b47acfd055dd2b001680769ff739-cfbf74e0.zZKgtjQ__Z2rpK0S.webp)](https://docs.pingcap.com/ja/tidb/stable/tidb-architecture)

画像出典: 「TiDB Docs」[https://docs.pingcap.com/ja/tidb/stable/tidb-architecture](https://docs.pingcap.com/ja/tidb/stable/tidb-architecture)

-   TiDB server  
    TiDB server は SQL パースや最適化、接続エンドポイントの公開を行っているサーバです。
    
-   Placement Driver（PD） server  
    クラスタ全体のメタデータを管理するサーバです。クラスタ内の TiKV ノード数やストレージの空き容量などクラスタ管理上重要なデータを保持しており、ダッシュボードもこのサーバ上で動作しています。
    
-   Storage servers
    
    -   TiKV server  
        データを保存する分散キーバリューストアです。
        
    -   TiFlash server  
        データを列指向で保存し、主に分析処理に利用されるサーバです。  
        これがあることで OLAP も高速に実行できるようになっています。
        

## 実際に Mac 上で動かしてみる

### スペック

Plain textcontent\_copy

```
❯ sw_vers
ProductName:		macOS
ProductVersion:		14.7

❯ sysctl machdep.cpu.brand_string
machdep.cpu.brand_string: Apple M2
```

1\. セットアップ

TiUP をインストールする

Plain textcontent\_copy

```
curl --proto '=https' --tlsv1.2 -sSf https://tiup-mirrors.pingcap.com/install.sh | sh

Successfully set mirror to https://tiup-mirrors.pingcap.com
Detected shell: zsh
Shell profile:  /Users/user/.zshrc
/Users/user/.zshrc has been modified to add tiup to PATH
open a new terminal or source /Users/user/.zshrc to use it
Installed path: /Users/{ユーザ名}/.tiup/bin/tiup
===============================================
Have a try:     tiup playground
===============================================
```

shell を読み込む

Plain textcontent\_copy

```
source ~/.zshrc
```

2\. クラスタを起動してみる

起動させる

Plain textcontent\_copy

```
tiup playground

❯ tiup playground

A new version of playground is available:  -> v1.16.0

    To update this component:   tiup update playground
    To update all components:   tiup update --all

The component `playground` version  is not installed; downloading from repository.
download https://tiup-mirrors.pingcap.com/playground-v1.16.0-darwin-arm64.tar.gz 8.11 MiB / 8.11 MiB 100.00% ? MiB/s

Note: Version constraint  is resolved to v8.3.0. If you'd like to use other versions:

    Use exact version:      tiup playground v7.1.0
    Use version range:      tiup playground ^5
    Use nightly:            tiup playground nightly

Start pd instance:v8.3.0
The component `pd` version v8.3.0 is not installed; downloading from repository.
download https://tiup-mirrors.pingcap.com/pd-v8.3.0-darwin-arm64.tar.gz 47.90 MiB / 47.90 MiB 100.00% 122.61 MiB/s
Start tikv instance:v8.3.0
The component `tikv` version v8.3.0 is not installed; downloading from repository.
download https://tiup-mirrors.pingcap.com/tikv-v8.3.0-darwin-arm64.tar.gz 41.75 MiB / 41.75 MiB 100.00% 136.10 MiB/s
Start tidb instance:v8.3.0
The component `tidb` version v8.3.0 is not installed; downloading from repository.
download https://tiup-mirrors.pingcap.com/tidb-v8.3.0-darwin-arm64.tar.gz 76.68 MiB / 76.68 MiB 100.00% 107.21 MiB/s
Waiting for tidb instances ready
127.0.0.1:4000 ... Done
The component `prometheus` version v8.3.0 is not installed; downloading from repository.
download https://tiup-mirrors.pingcap.com/prometheus-v8.3.0-darwin-arm64.tar.gz 118.75 MiB / 118.75 MiB 100.00% 99.08 MiB/s
download https://tiup-mirrors.pingcap.com/grafana-v8.3.0-darwin-arm64.tar.gz 59.93 MiB / 59.93 MiB 100.00% 118.32 MiB/s
Start tiflash instance:v8.3.0
The component `tiflash` version v8.3.0 is not installed; downloading from repository.
download https://tiup-mirrors.pingcap.com/tiflash-v8.3.0-darwin-arm64.tar.gz 76.56 MiB / 76.56 MiB 100.00% 104.53 MiB/s
Waiting for tiflash instances ready
127.0.0.1:3930 ... Done

🎉 TiDB Playground Cluster is started, enjoy!

Connect TiDB:    mysql --comments --host 127.0.0.1 --port 4000 -u root
TiDB Dashboard:  http://127.0.0.1:2379/dashboard
Grafana:         http://127.0.0.1:3000
```

pd, tikv, tidb, prometheus, grafana, tiflash のバイナリが download されました。

専用の dashboard や grafana も起動してすぐ閲覧できます。

TiDB Dashboard 画面

![ざっくり TiDB 入門してみたの画面（2）](/_astro/03-ff7ffe2ffbde99aad08eb5afcc35f6a4-1024x551-1a218dc2.h-5mqbdf_2fumqx.webp)

grafana 画面

![ざっくり TiDB 入門してみたの画面（3）](/_astro/04-88d44630230fa5d2934c1518b4ee5d0e-1024x552-3ce46f54.BYpAwb8n_1Sabmm.webp)

3\. mysql client でアクセスしてクエリを叩いてみる

mysql client を install する

Plain textcontent\_copy

```
brew install mysql-client
```

TiDB へアクセスする

Plain textcontent\_copy

```
mysql --comments --host 127.0.0.1 --port 4000 -u root
```

DB 作成する

Plain textcontent\_copy

```
CREATE DATABASE test_db;

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| INFORMATION_SCHEMA |
| METRICS_SCHEMA     |
| PERFORMANCE_SCHEMA |
| mysql              |
| sys                |
| test               |
| test_db            |
+--------------------+
7 rows in set （0.00 sec）
```

Table 作成する

Plain textcontent\_copy

```
USE test_db;
CREATE TABLE users （
  id INT AUTO_INCREMENT PRIMARY KEY,
  first_name VARCHAR（50）,
  last_name VARCHAR（50）,
  email VARCHAR（100）
）;

mysql> SHOW TABLES;
+-------------------+
| Tables_in_test_db |
+-------------------+
| users             |
+-------------------+
1 row in set （0.00 sec）
```

データ 追加する

Plain textcontent\_copy

```
INSERT INTO users （first_name, last_name, email）
VALUES
（'john', 'Doe', 'john.Doe@example.com'）,
（'Jane', 'Johnson', 'jane.Johnson@example.com'）,
（'Robert', 'Smith', 'robert.smith@example.com'）;
```

データ 取得

Plain textcontent\_copy

```
SELECT * FROM users;

+----+------------+-----------+--------------------------+
| id | first_name | last_name | email                    |
+----+------------+-----------+--------------------------+
|  1 | john       | Doe       | john.Doe@example.com     |
|  2 | Jane       | Johnson   | jane.Johnson@example.com |
|  3 | Robert     | Smith     | robert.smith@example.com |
+----+------------+-----------+--------------------------+
3 rows in set （0.00 sec）
```

EXPLAIN 実行する

Plain textcontent\_copy

```
mysql> EXPLAIN SELECT * FROM users;
+-----------------------+---------+-----------+---------------+--------------------------------+
| id                    | estRows | task      | access object | operator info                  |
+-----------------------+---------+-----------+---------------+--------------------------------+
| TableReader_5         | 3.00    | root      |               | data:TableFullScan_4           |
| └─TableFullScan_4     | 3.00    | cop[tikv] | table:users   | keep order:false, stats:pseudo |
+-----------------------+---------+-----------+---------------+--------------------------------+
2 rows in set （0.00 sec）
```

4\. クラスタをスケールアウトしてみる

現状、それぞれのコンポーネントが1台ずつ起動している

![ざっくり TiDB 入門してみたの画面（4）](/_astro/05-7d5ee06c1ff100c858d7352e26c27355-1024x440-1b81864f.iqN_USV1_Zwp0T2.webp)

TiDB server をスケールアウトして2台追加してみる

Plain textcontent\_copy

```
❯ tiup playground scale-out --db 2
To connect new added TiDB: mysql --comments --host 127.0.0.1 --port 58588 -u root -p （no password）
To connect new added TiDB: mysql --comments --host 127.0.0.1 --port 58611 -u root -p （no password）
```

bashboard で確認すると2台追加されている

![ざっくり TiDB 入門してみたの画面（5）](/_astro/06-3ed3c726ad0ec9977c67e45b820386f4-1024x151-f790de5b.Btp9l5jg_Z27wfwW.webp)

次は TiKV も2台追加してみる

Plain textcontent\_copy

```
❯ tiup playground scale-out --kv 2
```

TiKV もスケールアウトし2台追加されました

![ざっくり TiDB 入門してみたの画面（6）](/_astro/07-aac55a9dfe822651ef4ab05c70ec1238-1024x155-87ebbb67.Ky9RChs8_1hhp5l.webp)

5\. クラスタをスケールインしてみる

まずはスケールインするインスタンスのプロセス ID を確認する

Plain textcontent\_copy

```
❯ tiup playground display
Pid    Role     Uptime
--- ---- ------
79048  pd       1h9m58.2484515s
79049  tikv     1h9m58.233007791s
81427  tikv     31m28.505631958s
81428  tikv     31m28.493725s
79050  tidb     1h9m58.21935775s
80680  tidb     42m47.360035292s
80681  tidb     42m44.33974025s
79058  tiflash  1h9m49.716907125s
```

80680の TiDB server をスケールインする

Plain textcontent\_copy

```
❯ tiup playground scale-in --pid 80680
scale in tidb success
```

減りましたね

![ざっくり TiDB 入門してみたの画面（7）](/_astro/08-a050a9cc0c1a1ef8aacca6784c72e393-1024x116-e3f6c8ab.C-SnnNWZ_2skEeI.webp)

81428の TiKV もスケールインしてみます

Plain textcontent\_copy

```
❯ tiup playground scale-in --pid 81428
tikv will be stop when tombstone
```

TiKV はデータを持っているため、すぐ削除はしてくれないようですね  
このあたりは別のオペレーションが必要そうです

![ざっくり TiDB 入門してみたの画面（8）](/_astro/09-a073a62ea7e81c2c84d2cfed175f2cd1-1024x148-db7043c6.B-Axp-SF_cIxqX.webp)

## まとめ

ざっくり Mac 上で TiUP コマンドを使って TiDB を動かしてみました。tiup playground 自体はローカルでの開発やテスト用のクラスタを作成するのに便利なコマンドです。TiDB server や TiKV 以外にも Placement Server や TiFlash もスケールさせることができます。

TiDB Cloud もありますが、まずはローカル環境で実行させてみて最低限の TiDB の仕組みから理解するのが良さそうですね。  
今後も TiDB の機能について調べてみたいと思います。

## この記事を書いた人

[![](/_astro/noicon.CTHOhNiB_Z24aAgM.webp)](/authors/arai/)

### [arai](/authors/arai/)

araiのプロフィールと執筆記事をご覧いただけます。

[プロフィールと記事一覧](/authors/arai/)