Redis 해시
Redis 해시 (Redis hashes)
Redis 해시(hash)는 field-value 쌍의 모음으로 구성된 레코드 타입이에요. 기본적인 객체를 표현하거나, 카운터(counter)들의 그룹을 저장하는 데 쓸 수 있어요. 이번 페이지에서는 해시의 기본 연산부터, 라운드 트립을 줄이는 방법, 그리고 필드별 TTL까지 하나씩 살펴볼게요.
해시 기본 사용법
Redis 해시는 field-value 쌍의 모음으로 이뤄진 레코드 타입이에요. 기본적인 객체를 나타내거나 카운터 그룹을 저장하는 데 쓸 수 있고, 이 외에도 다양한 방식으로 활용할 수 있어요.
기본적으로 HSET으로 해시의 여러 필드를 설정하고, HGET으로 단일 필드를 가져와요.
> HSET bike:1 model Deimos brand Ergonom type "Enduro bikes" price 4972
(integer) 4
> HGET bike:1 model
"Deimos"
> HGET bike:1 price
"4972"
> HGETALL bike:1
1) "model"
2) "Deimos"
3) "brand"
4) "Ergonom"
5) "type"
6) "Enduro bikes"
7) "price"
8) "4972"
Python으로는 이렇게 써요.
res1 = r.hset(
"bike:1",
mapping={
"model": "Deimos",
"brand": "Ergonom",
"type": "Enduro bikes",
"price": 4972,
},
)
print(res1)
# >>> 4
res2 = r.hget("bike:1", "model")
print(res2)
# >>> 'Deimos'
res3 = r.hget("bike:1", "price")
print(res3)
# >>> '4972'
res4 = r.hgetall("bike:1")
print(res4)
# >>> {'model': 'Deimos', 'brand': 'Ergonom', 'type': 'Enduro bikes', 'price': '4972'}
Node.js로는 이렇게 써요.
const res1 = await client.hSet(
'bike:1',
{
'model': 'Deimos',
'brand': 'Ergonom',
'type': 'Enduro bikes',
'price': 4972,
}
)
console.log(res1) // 4
const res2 = await client.hGet('bike:1', 'model')
console.log(res2) // 'Deimos'
const res3 = await client.hGet('bike:1', 'price')
console.log(res3) // '4972'
const res4 = await client.hGetAll('bike:1')
console.log(res4)
/*
{
brand: 'Ergonom',
model: 'Deimos',
price: '4972',
type: 'Enduro bikes'
}
*/
해시는 객체를 표현할 때 편리하지만, 실제로 해시 안에 넣을 수 있는 필드 수에는 실질적인 제한이 없어요(사용 가능한 메모리만큼). 그래서 애플리케이션 안에서 해시를 다양한 방식으로 쓸 수 있습니다.
여러 필드 가져오기: HMGET
HSET은 해시의 여러 필드를 설정하고, HGET은 단일 필드를 가져와요. HMGET은 HGET과 비슷하지만 값의 배열을 반환해요. 여러 필드를 한 번에 가져와 서버 왕복(round trips)을 줄일 때 유용하죠.
> DEL bike:1
(integer) 1
> HSET bike:1 model Deimos brand Ergonom type "Enduro bikes" price 4972
(integer) 4
> HMGET bike:1 model price
1) "Deimos"
2) "4972"
# Recreate the bike:1 hash so this example runs on its own.
r.delete("bike:1")
r.hset(
"bike:1",
mapping={
"model": "Deimos",
"brand": "Ergonom",
"type": "Enduro bikes",
"price": 4972,
},
)
res5 = r.hmget("bike:1", ["model", "price"])
print(res5)
# >>> ['Deimos', '4972']
HSET은 기존 필드 값을 덮어써요. HSETNX를 쓰면 필드가 이미 존재할 때 설정을 건너뛸 수 있어요. HINCRBY는 카운터로 쓰이는 정수 필드를 원자적으로 증가시켜요.
> HINCRBY bike:1:stat sales 10
(integer) 10
> HINCRBY bike:1:stat sales 5
(integer) 15
필드별 만료 (TTL)
해시의 **개별 필드에 TTL(만료 시간)**을 설정할 수도 있어요. 센서 데이터처럼 자주 갱신되는 해시에서 특정 필드만 만료시키고 싶을 때 유용하죠. 이 기능은 Redis 7.4부터 사용할 수 있어요 (확인 필요).
> DEL sensor:sensor1
(integer) 1
> HSET sensor:sensor1 air_quality 256 battery_level 89
(integer) 2
> HPEXPIRE sensor:sensor1 60000 FIELDS 1 air_quality
1) (integer) 1
> HPTTL sensor:sensor1 FIELDS 1 air_quality
1) (integer) 60000
HPEXPIRE는 지정한 필드의 TTL을 밀리초 단위로 설정해요.HPTTL은 필드의 남은 TTL을 밀리초로 반환해요.- 필드 단위 만료는 초 단위의
HEXPIRE/HTTL로도 할 수 있어요.
Python으로는 이렇게 써요.
# Set the TTL of the 'air_quality' field in milliseconds.
r.hset("sensor:sensor1", mapping={"air_quality": 256, "battery_level": 89})
r.hpexpire("sensor:sensor1", 60000, "air_quality")
# >>> [1]
# Retrieve the remaining TTL in milliseconds.
r.hpttl("sensor:sensor1", "air_quality")
# >>> [60000]
정리 (Summary)
- 해시는 field-value 쌍의 모음으로, 객체를 표현하거나 카운터 그룹을 저장하기에 좋아요.
HSET/HGET/HGETALL로 기본적인 읽기/쓰기를 하고,HMGET으로 한 번에 여러 필드를 가져와 round trips를 줄일 수 있어요.- 해시의 필드 수에는 실질적 제한이 없어요(메모리만 충분하다면).
- Redis 7.4+에서는 필드별 TTL을 설정해 특정 필드만 만료시킬 수도 있어요.
해시는 Redis에서 가장 유연하게 쓰이는 데이터 타입 중 하나예요. 객체 캐싱, 세션 저장, 카운터 집계 등에 자주 활용됩니다.
더 알아보기 (Learn more)
- Redis 해시 명령어 참조 (HSET, HGET, HMGET, HGETALL, HINCRBY 등 33개 명령)
- 데이터 타입 비교 — 다른 데이터 타입과의 차이
- Redis sets — 멤버십과 집합 연산이 필요할 때