AWS Infra

[ Python ] Python을 이용한 ElastiCache Redis Hash Data Export & Import

Pydole 2023. 2. 28. 11:37

 

 ElasiCache Redis를 운영하면서 "noeviction" 데이터 보관용으로 운영하면서 주기적으로 데이터를 Export 해야할 필요가

생겼다. 데이터에 접근할 있어, 분석이나 재처리 업무시 사용할 수 있고, 2차 백업용으로도 사용할 수 있겠다.

 


 

Sample Hash Data

 

 

 

 


Export to Json File

 

import redis
import json


# 접속옵션으로 decode_responses=True 사용할 경우, decode를 않해도 된다.


rd = redis.StrictRedis(host='localhost', port=6379, db=0)

allhash = [ x.decode() for x in rd.scan_iter('*') ]

redisdct = {}

for h in allhash:
    kdct = {}
     
    for key, value in rd.hgetall(h).items():
        kdct[key.decode()] = value.decode()
        redisdct[h] = kdct

with open("redis_hash_key.json", "w") as json_file:
    json.dump(redisdct, json_file)

 

 

with open("redis_hash_key.json") as json_file:
    data = json_file.read()

print(data)

{"hash_B": {"b": "20", "d": "40"}, "hash_A": {"a": "10", "c": "30"}}

 

 

 


 

 

Import to Redis

 

import redis
import json

rd = redis.StrictRedis(host='localhost', port=6379, db=0)

with open("redis_hash_key.json") as json_file:
    jsondata = json_file.read()

dctdata = json.loads(jsondata)

for h, k in dctdata.items():
    rd.hset(h, mapping=k)
    

# dictionary import : hmset → hset with mapping