[add a subtitle] Redis Hashes Explained

Redis University 영상에 자막 달기

GARIMOO
garimoo
16 min readApr 18, 2020

--

https://youtu.be/-agsJUihrWw
Best wishes!

Redis University에 올라오는 영상에 댓글을 달아보기로 했다. 고작 6분 남짓한 영상에 자막을 추가하는 데에 꼬박 네시간이 걸렸다. 원래 영자막도 없기 때문에 직접 들으면서 영자막을 타이핑하고, 그걸 한국어로 바꿔서 써놓고, 싱크맞춰서 추가하는게 여간 복잡한게 아니다. 오역도 많고 의역도 많지만 처음이니까 당연한 거라고 생각하며, 앞으로 올라오는 모든 영상에 한글 자막을 달 예정이다! 화이이이팅💪🏻

Hello. today we’re going to learn about hashes.

안녕하세요. 오늘은 해시에 대해서 배워보겠습니다.

an especially useful Redis data structure.

해시는 아주 유용한 레디스의 자료구조입니다.

In this segment, I’ll explain what hashes are and I’ll show you how to use them to model the main objects in an application.

이 강의에서 저는 해시가 무엇인지, 그리고 어플리케이션의 메인 객체에서 어떻게 사용할 수 있는지에 대해 설명하겠습니다.

Hashes are collections of field-value pairs and look a lot like a JSON object a java hash map or a python dictionary.

해시는 필드-값 쌍으로 이루어진 집합이며 JSON 객체, JAVA의 HashMap, Python의 Dictionary와 비슷합니다.

Redis hashes are also mutable.

레디스의 해시는 변경이 가능합니다.

We can add, change, increment and remove field value pairs at any time not just at the initial declaration.

초기 선언 뿐 아니라 언제든지 필드-값 쌍을 추가, 변경, 삭제할 수 있습니다.

Hashes store field, values as strings.

해시는 필드-값을 문자열로 저장합니다.

Which means that they are flat.

이는 해시가 플랫하다는 것을 의미합니다.

There are no nested arrays or objects.

중첩된 배열이나 객체를 포함하지 않습니다.

Also, we do not need to predefined field names of Redis hashes and as such we can add and remove fields as needed.

또한 필드의 이름을 먼저 정의할 필요가 없기 때문에 필요에 따라 필드를 더하거나 제외할 수 있습니다.

While Redis hashes are schemaless, you can still think of them as lightweight objects or as rows in a relational database table.

레디스의 해시는 스키마가 없지만, 이를 가벼운 객체 또는 관계형 데이터베이스에서의 한 행으로 생각할 수 있습니다.

To explore Redis hashes in practice, let’s think about how we’d model a player in a fictional online role-playing game mazes and minotaurs.

레디스 해시를 실제로 사용해보기 위해, 미로와 미노타우르스라는 가상의 온라인 롤플레잉 게임을 모델링하는 방법을 생각해보겠습니다.

In a role-playing game, players live die and reborn

게임 속에서 플레이어는 살아가고, 죽고, 다시 태어납니다.

And this cycle of life is reflected in health points, armor, abilities and medals.

이 인생 사이클은 포인트, 갑옷, 능력치, 메달 등에 반영됩니다.

We’ll store this information in a hash.

우리는 이 정보들을 해시에 저장할 것입니다.

With every player getting their own hash instance.

모든 플레이어는 각자 해시 인스턴스 한 개를 갖게 됩니다.

We’ll update this player’s hash with new information create temporary fields and use built-in functionality to increment numerical values and update strings.

우리는 이 플레이어의 해시에 새로운 데이터를 업데이트하고, 임시로 필드를 생성하며, 숫자를 증가시킬 수 있는 내장 함수를 사용하고, 문자열을 업데이트할 것입니다.

Enter the player artexius, the proud elven knight.

자랑스러운 엘프 기사, 플레이어 Artexius가 들어왔습니다.

For this first example, we’ll create a hash starting off with the fields name, race, level, health points, and gold.

이 첫 번째 예제에서 우리는 이름, 혈족, 레벨, 포인트, 골드라는 필드를 가진 해시를 생성할 것입니다.

To create this hash we’ll use the commands HSET.

이 해시를 만들기 위해 HSET이라는 커맨드를 사용합니다.

The first argument to the HSET command is the key name we’ll use to access the hash.

HSET 커맨드의 첫 번째 인수는 해시에 접근할 수 있는 키의 이름입니다.

In this case, it’s player:42.

이 경우, 이는 player:42 입니다.

Here we’re using a common Redis key naming convention.

여기서는 일반적인 레디스 키 명명 규칙을 사용했습니다.

We start with the word player to indicate what type of thing we’re storing.

키 이름을 player라는 단어로 시작해서 어떤 타입을 저장할건지 나타내며,

We then followed with a colon the ID of this player.

: 뒤에 이 플레이어의 ID를 추가했습니다.

The colon separates the various parts of the key name going from least specific on the left to most specific on the right.

콜론은 키 이름에서 두 파트를 분리하며, 추상적인 값을 왼쪽에, 구체적인 값을 오른쪽에 배치합니다.

After specifying the key, we had as many field values pairs as if you want.

키를 정의한 다음, 원하는 만큼의 필드-값 쌍을 적어줍니다.

When we run this command, Redis returns 5, indicating the number of fields saved to the hash.

이 커맨드를 실행하면 레디스는 5를 반환하며, 이는 해시에 저장된 필드의 개수를 의미합니다.

We’ve now created a Redis hash.

이제 레디스 해시를 한 개 만들었습니다.

Our first player for the mages and minotaurs.

미로와 미노타우르스 게임의 첫 번째 플레이어입니다.

Now let’s see how to update and delete fields within a Redis hash.

이제 레디스 해시를 업데이트하고 삭제하는 방법에 대해서 알아봅시다.

Imagine that player Artexius is having an epic battle with a wizard and received a thunderbolt spell to the head.

우리의 플레이어 Artexius가 마법사와 전투를 하다가, 머리에 번개를 맞았다고 상상해봅시다.

In the game, he’ll have a status of dazed.

게임 속에서, 그는 기절 상태가 됩니다.

To reflect this game state in the Redis hash, we’ll add the field value pair status dazed to the player’s hash instance.

이를 해시에 나타내기 위해 해시 인스턴스의 필드-값 쌍에 status-dazed 를 추가할 것입니다.

Here again we’ll use the HSET command to add a new field value pair.

다시 HSET 커맨드를 사용해서 새로운 필드-값 쌍을 추가합니다.

So the command will run as HSET player:42 status dazed.

HSET player:42 status dazed라는 커맨드를 입력해봅시다.

What happens when our player no longer has the status of dazed will want to remove the status field from the hash instance.

플레이어는 상태가 더이상 ‘기절’이 아닐 때 해시 인스턴스에서 이 필드를 삭제하고 싶어질 것입니다.

To delete a field value pair from a Redis hash, we use the command HDEL.

레디스 해시에서 필드-값 쌍을 삭제하고 싶을때, HDEL 커맨드를 사용합니다.

The command is HDEL player:42 status.

HDEL player:42 status 처럼 사용하며,

Now the player:42 hash instance no longer has a dazed to status.

이제 player:42 해시 인스턴스는 더이상 ‘기절’ 상태가 아니게 됩니다.

Our Artexius lives to quest another day.

우리의 Artexius는 다른 퀘스트를 진행하며 살아가겠죠.

Getting data from a hash is just as easy as setting it.

해시에서 데이터를 가져오는 것은 데이터를 입력하는 것 만큼 쉽습니다.

Suppose we need to retrieve Artexius level for that we’ll need to use the HGET command.

Artexius의 레벨을 검색하기 위해서는, HGET 커맨드가 필요할 것입니다.

The command is HGET player:42 and then the field we want, level.

HGET player:42 뒤에 우리가 필요로 하는 필드인 level을 적어줍니다.

To get all the fields and values from our Redis hash, use the HGETALL command.

해시에서 모든 필드와 값을 반환하기 위해서는 HGETALL 커맨드를 사용할 수 있습니다.

We’ll run HGETALL player:42

HGETALL player:42 를 입력해줍니다.

This will return all fields and values contained within the hash.

이 커맨드는 해시 내의 모든 필드와 값을 리턴합니다.

Now, in many role-playing games, players received gold after completing objectives or defeating enemies.

많은 롤플레잉 게임에서 플레이어는 목표를 성취하거나 적을 패배시켰을 때 골드를 받게 됩니다.

We’ll need to be able to increase the amount of gold a player has whenever this occurs.

우리는 이런 상황에서 플레이어의 골드를 증가시킬 수 있어야 합니다.

Guess what? there’s a command for that.

그거 아시나요? 이를 위한 커맨드가 존재합니다.

It’s called an Hincryby, and it increments the value of a particular hash field.

HINCRYBY라는 이름의 커맨드이며, 특정 해시 필드의 값을 증가시킵니다.

we enter HINCRYBY player:42 gold and the increment value.

HINCRYBY player:42 gold 그리고 증가시킬 값을 입력합니다.

Let’s increment the value assigned to the gold field by 120

골드 필드에 할당된 값을 120만큼 증가시켜봅시다.

Okay. Let’s talk about the performance characteristics of this hash commands.

좋아요. 이제 해시 커맨드의 성능에 대해서 이야기해봅시다.

Most hash commands are O(1).

대부분의 해시 커맨드는 O(1)입니다.

Which means they will always perform a task in a constant amount of time

이는 대부분의 작업을 항상 일정한 시간 안에 수행한다는 것을 의미합니다.

regardless of the size of the hash.

해시의 크기와 상관 없이 말입니다.

Constant time commands are as efficient as it gets

이런 커맨드들은 항상 효율적입니다.

The HGETALL command is o(n) with n being the number of fields within a hash.

HGETALL 커맨드는 O(n)이며 n은 해시 내부의 필드 수를 뜻합니다.

This means that the amount of time for the task to complete is dependent on how many fields it has to retrieve.

이는 작업을 수행하는 시간이 해시가 몇개의 필드를 가지고 있느냐에 따라 달라지는 것을 의미합니다.

In this case the n of o(n) is the number of fields that hash contains.

이 경우 n은 해시가 가지고 있는 필드의 개수를 의미합니다.

HGETALL is practical for relatively small hashes such as our player’s hash.

HGETALL은 비교적 작은 해시들에서 유용합니다. 우리 플레이어의 해시처럼요.

For hashes containing thousands of fields or more,

해시가 천개 이상의 필드를 가지고 있다면,

It’s usually most efficient to select the exact fields you want using HGET, rather than retrieving all of the data with HGETALL, or HSCAN.

일반적으로 원하는 필드를 HGET를 이용해서 검색하는 것이 전체 데이터를 검색하는 HGETALL이나 HSCAN보다 효율적입니다.

Okay, let’s review.

자, 이제 리뷰해보겠습니다.

We’ve just explored how we can use Redis hashes to represent player objects in an online role-playing game.

우리는 방금 레디스의 해시를 이용해서 온라인 롤플레잉 게임에서 플레이어의 객체를 나타낼 수 있는 방법을 알아보았습니다.

We’ve learned that Redis hashes exist as collections of field-value pairs.

레디스 해시는 필드-값 쌍으로 이루어져 있다는 것을 배웠고,

We created and updates a hashes using HSET.

HSET을 이용해서 해시를 생성하고, 업데이트했습니다.

We retrieved data with HGET and HGETALL.

HGET과 HGETALL을 이용해서 데이터를 검색했습니다.

Fields can be deleted with HDEL

필드는 HDEL 커맨드로 삭제할 수 있습니다.

Lastly, we incremented numerical values using hincryby.

마지막으로, HINCRYBY라는 커맨드를 사용해서 숫자값을 증가시켰습니다.

As useful as hashes are, they aren’t the be-all and end-all for object storage and Redis.

해시가 유용하긴 하지만, 오브젝트 스토리지와 레디스에서 모든 값을 저장할 수 있는 것은 아닙니다.

If you’re dealing with nested structures or JSON, check out RedisJSON.

중첩 구조 또는 JSON을 다루고 있다면 RedisJSON을 확인해보세요.

RedisJSON is a Redis module that implements the JSON data interchange standard as a native data type.

RedisJSON은 JSON을 기본 데이터 유형으로 사용하기 위해 표준을 교환하는 레디스 모듈입니다.

It implements an efficient storage update and retrieval of JSON data in Redis.

이 모듈은 레디스에서 효율적으로 JSON 데이터를 업데이트하고, 검색할 수 있도록 구현되었다.

To learn more about Redis hashes, check our free online course introduction to Redis data structures.

레디스의 해시에 대해서 더 알고 싶다면, 레디스의 데이터구조에 대해 소개하는 우리의 무료 강의를 들어보세요.

As part of Redis University, our online learning platform for all things Redis.

레디스에 대한 모든 온라인 교육을 제공하는 플랫폼인 RedisUniversity에서 확인할 수 있습니다.

Thank you for joining me in designing mages and minotaurs.

미로와 미노타우루스 디자인에 함께 해주셔서 감사합니다.

I hope to go on another quest of you again soon.

당신의 다른 퀘스트에서 곧 만나기를 바라겠습니다.

--

--