2023년 12월 1일 금요일

timescaledb 사용하기

 1. docker compose 파일 작성

version: "3.8"

services:
  timescaledb:
    image: timescale/timescaledb:latest-pg14
    container_name: timescale
    hostname: timescaledb
    restart: always
    ports:
      - ${TIMESCALEDB_PORT}:5432
    volumes:
      - ./${TIMESCALEDB_DATA_STORE}:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${TIMESCALEDB_PASSWORD}
      POSTGRES_USER: ${TIMESCALEDB_USER}
      POSTGRES_DB: ${TIMESCALEDB_DB}
  adminer:
    image: adminer:4.8.1
    container_name: adminer
    restart: always
    ports:
      - ${ADMINER_PORT}:8080

2. 동일 폴더에 .env파일 작성

# timescaledb
TIMESCALEDB_PORT=5432
TIMESCALEDB_DATA_STORE=timescaledb/
TIMESCALEDB_PASSWORD=timescaledb
TIMESCALEDB_USER=timescale
TIMESCALEDB_DB=timescale_database

# adminer
ADMINER_PORT=8087

3. docker compose up 실행

4. python 코드로 접속 여부 확인

import psycopg2
from pgcopy import CopyManager
# Structure of the connection string:
# "postgres://username:password@host:port/dbname"
CONNECTION = "postgres://timescale:timescaledb@localhost:5432/timescale_database"
conn = psycopg2.connect(CONNECTION)
cursor = conn.cursor()

for id in range(1, 4, 1):
     data = (id,)
     # create random data
     simulate_query = """SELECT generate_series(now() - interval '24 hour', now(), interval '5 minute') AS time,
                        %s as sensor_id,
                        random()*100 AS temperature,
                        random() AS cpu
                     """
     cursor.execute(simulate_query, data)
     values = cursor.fetchall()
     # column names of the table you're inserting into
     cols = ['time', 'sensor_id', 'temperature', 'cpu']
     # create copy manager with the target table and insert
     mgr = CopyManager(conn, 'sensor_data', cols)
     mgr.copy(values)

conn.commit()

5. chrome열어서 localhost:8087 접속하여 table생성 여부 체크

6. docker container ls --all 로 container 체크해서 아래 확인

2b2340a3b640   timescale/timescaledb:latest-pg14   "docker-entrypoint.s…"   7 days ago   Up 7 days   0.0.0.0:5432->5432/tcp   timescale
bc41c6ad6171   adminer:4.8.1                       "entrypoint.sh php -…"   7 days ago   Up 7 days   0.0.0.0:8087->8080/tcp   adminer


[참고] 

1. Postres for time series data, Medium