本ブログの記事にはPRが含まれています。

お試し用サンプルデータベース構築方法

あなた

データ分析をやりたいけど、肝心なデータベースがないから試せなくて困る。。

さくる

データベースがないと試すのも
意外と簡単にサンプルデータベース作れるんだよ!

本記事では、これからデータ分析を試してみたいという方が試せるようなサンプルデータベースを作成する方法を紹介します。本ブログでも例題として利用するものになっているので、もし本ブログで勉強したいという方は、ぜひ、こちらを参考にデータベース構築をしてみてください。

目次

今回作成するデータベース環境の紹介

今回作成するデータベース構築に関する説明の構築環境について説明します。

OSWindows 11
※説明はWindows環境ですがMac環境でも同様の環境は構築可能です。
DBPostgreSQL
コンテナ実行環境Docker Desktop

具体的なデータベースの構築

それでは実際にデータベースの構築を行います。

STEP
Docker Desktopをインストールする

Docker Desktopをインストールしましょう。

具体的な手順

Docker Desktopダウンロードサイトを開く

Docker
Docker Desktop: The #1 Containerization Tool for Developers | Docker Docker Desktop is collaborative containerization software for developers. Get started and download Docker Desktop today on Mac, Windows, or Linux.

②「.exe」ファイルをダウンロードする

「Download Docker Desktop」を押下して、自身の環境を選択してください。

③ダウンロードした「.exe」ファイルを開く

④Docker Desktopをインストールする

ダイアログが表示されるので、「OK」を押下してインストールを行ってください。

⑤インストールされていることを確認する

最後にPowerShellを開き、下記コマンドを実行しましょう。
どちらもバージョンが表示されたら、問題なくインストールできています。

docker --version
docker compose version
STEP
作業フォルダを作成する

作業フォルダを作成しましょう。

フォルダ作成例

C:\
└─ work
  └─ olist-postgres
    └─ data

STEP
Olistデータをダウンロードする

KaggleからOlistのデータセットをダウンロードします。

具体的な手順

Olist公式投稿を開く

②データセットをダウンロードする

画面右上の「Download」>「Download dataset as zip」を押下してデータセットをダウンロードしましょう。

③お好きな方法でサインインする

もし下記が表示されたら、お好きな方法でサインインしてください。
その後、再度②の操作を実施して、データセットをダウンロードしましょう。

④ダウンロードした「.zip」ファイルを解凍(展開)する

⑤展開したフォルダ内にある「.csv」をSTEP2の作業フォルダに移動する

STEP
PostgreSQL用のフォルダを作成する

STEP2で作成したolist-postgreshフォルダの中に「init」フォルダを作成しましょう。

フォルダ作成例

C:\
└─ work
  └─ olist-postgres
    └─ data

      └─ CSVファイル

    └─ init

STEP
docker-compose.ymlを作成する

docker-compose.ymlを作成して、設定しましょう。

具体的な手順

C:\work\olist-postgresの直下に、「docker-compose.yml」ファイルを作成する

フォルダ作成例

C:\
└─ work
  └─ olist-postgres

    └─ docker-compose.yml
    └─ data

      └─ CSVファイル

    └─ init

②「docker-compose.yml」を設定する

「docker-compose.yml」を開き、下記を記載してください。

services:
  postgres:
    image: postgres:17
    container_name: olist-postgres
    environment:
      POSTGRES_DB: olist
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./data:/data
      - ./init:/docker-entrypoint-initdb.d

volumes:
  postgres_data:

※こちらは学習用として下記の設定となっています。本番環境では利用しないようにお願いします。

DB名       olist
ユーザー   postgres
パスワード postgres
ポート     5432
STEP
テーブル作成SQLを作る

次にDB上に作成するテーブルの作成用SQLを用意しましょう。

真似すれば基本的には中身がわからなくても問題ないので、ご安心ください。

具体的な手順

C:\work\olist-postgres\initの直下に、01_create_tables.sqlファイルと02_load_data.sqlを作成する

フォルダ作成例

C:\
└─ work
  └─ olist-postgres

    └─ docker-compose.yml
    └─ data

      └─ CSVファイル

    └─ init

      └─ 01_create_tables.sql

      └─ 02_load_data.sql

01_create_tables.sqlに下記を記載する

-- ============================================================
-- Olist Brazilian E-Commerce Dataset
-- PostgreSQL Table Definitions
-- ============================================================


-- ------------------------------------------------------------
-- 1. customers
-- 元CSV: olist_customers_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE customers (
    customer_id VARCHAR(50) PRIMARY KEY,
    customer_unique_id VARCHAR(50) NOT NULL,
    customer_zip_code_prefix INTEGER,
    customer_city VARCHAR(100),
    customer_state VARCHAR(2)
);


-- ------------------------------------------------------------
-- 2. geolocation
-- 元CSV: olist_geolocation_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE geolocation (
    geolocation_zip_code_prefix INTEGER,
    geolocation_lat NUMERIC(10, 7),
    geolocation_lng NUMERIC(10, 7),
    geolocation_city VARCHAR(100),
    geolocation_state VARCHAR(2)
);


-- ------------------------------------------------------------
-- 3. sellers
-- 元CSV: olist_sellers_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE sellers (
    seller_id VARCHAR(50) PRIMARY KEY,
    seller_zip_code_prefix INTEGER,
    seller_city VARCHAR(100),
    seller_state VARCHAR(2)
);


-- ------------------------------------------------------------
-- 4. products
-- 元CSV: olist_products_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE products (
    product_id VARCHAR(50) PRIMARY KEY,
    product_category_name VARCHAR(100),
    product_name_length INTEGER,
    product_description_length INTEGER,
    product_photos_qty INTEGER,
    product_weight_g INTEGER,
    product_length_cm INTEGER,
    product_height_cm INTEGER,
    product_width_cm INTEGER
);


-- ------------------------------------------------------------
-- 5. product_category_translation
-- 元CSV: product_category_name_translation.csv
-- ------------------------------------------------------------

CREATE TABLE product_category_translation (
    product_category_name VARCHAR(100) PRIMARY KEY,
    product_category_name_english VARCHAR(100)
);


-- ------------------------------------------------------------
-- 6. orders
-- 元CSV: olist_orders_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE orders (
    order_id VARCHAR(50) PRIMARY KEY,
    customer_id VARCHAR(50) NOT NULL,
    order_status VARCHAR(30),
    order_purchase_timestamp TIMESTAMP,
    order_approved_at TIMESTAMP,
    order_delivered_carrier_date TIMESTAMP,
    order_delivered_customer_date TIMESTAMP,
    order_estimated_delivery_date TIMESTAMP,

    CONSTRAINT fk_orders_customer
        FOREIGN KEY (customer_id)
        REFERENCES customers(customer_id)
);


-- ------------------------------------------------------------
-- 7. order_items
-- 元CSV: olist_order_items_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE order_items (
    order_id VARCHAR(50) NOT NULL,
    order_item_id INTEGER NOT NULL,
    product_id VARCHAR(50) NOT NULL,
    seller_id VARCHAR(50) NOT NULL,
    shipping_limit_date TIMESTAMP,
    price NUMERIC(12, 2),
    freight_value NUMERIC(12, 2),

    PRIMARY KEY (
        order_id,
        order_item_id
    ),

    CONSTRAINT fk_order_items_order
        FOREIGN KEY (order_id)
        REFERENCES orders(order_id),

    CONSTRAINT fk_order_items_product
        FOREIGN KEY (product_id)
        REFERENCES products(product_id),

    CONSTRAINT fk_order_items_seller
        FOREIGN KEY (seller_id)
        REFERENCES sellers(seller_id)
);


-- ------------------------------------------------------------
-- 8. order_payments
-- 元CSV: olist_order_payments_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE order_payments (
    order_id VARCHAR(50) NOT NULL,
    payment_sequential INTEGER NOT NULL,
    payment_type VARCHAR(30),
    payment_installments INTEGER,
    payment_value NUMERIC(12, 2),

    PRIMARY KEY (
        order_id,
        payment_sequential
    ),

    CONSTRAINT fk_order_payments_order
        FOREIGN KEY (order_id)
        REFERENCES orders(order_id)
);


-- ------------------------------------------------------------
-- 9. order_reviews
-- 元CSV: olist_order_reviews_dataset.csv
-- ------------------------------------------------------------

CREATE TABLE order_reviews (
    review_id VARCHAR(50) NOT NULL,
    order_id VARCHAR(50) NOT NULL,
    review_score INTEGER,
    review_comment_title TEXT,
    review_comment_message TEXT,
    review_creation_date TIMESTAMP,
    review_answer_timestamp TIMESTAMP,

    PRIMARY KEY (
        review_id,
        order_id
    ),

    CONSTRAINT fk_order_reviews_order
        FOREIGN KEY (order_id)
        REFERENCES orders(order_id)
);

02_load_data.sqlに下記を記載する

-- ============================================================
-- Olist Brazilian E-Commerce Dataset
-- CSV Data Import
-- ============================================================


-- ------------------------------------------------------------
-- 1. customers
-- ------------------------------------------------------------

COPY customers (
    customer_id,
    customer_unique_id,
    customer_zip_code_prefix,
    customer_city,
    customer_state
)
FROM '/data/olist_customers_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 2. geolocation
-- ------------------------------------------------------------

COPY geolocation (
    geolocation_zip_code_prefix,
    geolocation_lat,
    geolocation_lng,
    geolocation_city,
    geolocation_state
)
FROM '/data/olist_geolocation_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 3. sellers
-- ------------------------------------------------------------

COPY sellers (
    seller_id,
    seller_zip_code_prefix,
    seller_city,
    seller_state
)
FROM '/data/olist_sellers_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 4. products
-- ------------------------------------------------------------

COPY products (
    product_id,
    product_category_name,
    product_name_length,
    product_description_length,
    product_photos_qty,
    product_weight_g,
    product_length_cm,
    product_height_cm,
    product_width_cm
)
FROM '/data/olist_products_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 5. product_category_translation
-- ------------------------------------------------------------

COPY product_category_translation (
    product_category_name,
    product_category_name_english
)
FROM '/data/product_category_name_translation.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 6. orders
-- customersより後に読み込む
-- ------------------------------------------------------------

COPY orders (
    order_id,
    customer_id,
    order_status,
    order_purchase_timestamp,
    order_approved_at,
    order_delivered_carrier_date,
    order_delivered_customer_date,
    order_estimated_delivery_date
)
FROM '/data/olist_orders_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 7. order_items
-- orders / products / sellersより後に読み込む
-- ------------------------------------------------------------

COPY order_items (
    order_id,
    order_item_id,
    product_id,
    seller_id,
    shipping_limit_date,
    price,
    freight_value
)
FROM '/data/olist_order_items_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 8. order_payments
-- ordersより後に読み込む
-- ------------------------------------------------------------

COPY order_payments (
    order_id,
    payment_sequential,
    payment_type,
    payment_installments,
    payment_value
)
FROM '/data/olist_order_payments_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);


-- ------------------------------------------------------------
-- 9. order_reviews
-- ordersより後に読み込む
-- ------------------------------------------------------------

COPY order_reviews (
    review_id,
    order_id,
    review_score,
    review_comment_title,
    review_comment_message,
    review_creation_date,
    review_answer_timestamp
)
FROM '/data/olist_order_reviews_dataset.csv'
WITH (
    FORMAT CSV,
    HEADER TRUE,
    DELIMITER ',',
    ENCODING 'UTF8'
);
STEP
PostgreSQLを起動する

PostgreSQLを初期起動を完了させてましょう。

初期起動のタイミングでテーブルも作成されます。

具体的な手順

①Docker Desktopを起動する

②Dockerの事前準備をする

①PowerShellを起動する

②下記を実行して「olist-postgres」フォルダに移動する

cd C:\work\olist-postgres

③dockerを初回起動する

下記コマンドで初回起動すると「olist-postgres」フォルダの中身を読み込んでDBの構築・テーブルの作成・データの挿入まで一括で行ってくれます。

docker compose up -d

問題なく実行されれば、下記のような表示となります。

もしエラーが発生したら…

もし下記エラーが発生したら、次のように対処しましょう。

①wslが動作しているか確認する

下記を実行してwslが動作しているかを確認しましょう。

wsl --status

もし下記のような表示となれば、wslがインストールされていないことが問題んである可能性が高いです。

②①でwslが動作していなかった場合は、下記を実行してwslをインストールする

wsl --install

③再起動する

インストールが正常に完了すると下記のように再起動を促されるので、再起動する

④wslが動作しているかを確認する

下記を実行して

wsl --status

実行結果で規定バージョン:〇と表示されば問題なく動作していることがわかります。

⑤再度STEP7の①から順番に対応を行う

問題が解決されていれば、DBの構築・テーブルの作成・データの挿入が行われるはずです。

STEP
動作確認する

データベースの構築は完了したので、正常にデータを取得できるか確認しましょう。

具体的な手順

①docker desktop起動する

docker desktopが起動していなければ、起動しましょう。

②PowerShellを開く

③PostgreSQLを起動する

下記を実行してPostgreSQLを開きましょう

docker exec -it olist-postgres psql -U postgres -d olist

④データが入っていること・SQLが実行できることを確認する

下記を実行してデータが問題なく抽出できることを確認しましょう。

・テーブル一覧を取得

\dt

・データの件数を確認する

SELECT COUNT(*)
FROM orders;

・実際にデータの中身を確認する

SELECT *
FROM customers
LIMIT 10;

分析を始めよう!

以上で、分析用のDBの構築とテーブルの作成が完了しました。

テーブルに格納されている情報を使ってデータ分析やデータ抽出などができるようになるので、実際に触ってみたり、本ブログで学んだことを試すのに使ってみてください。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

コメント

コメントする

目次