How to create key value pairs with Redis


Redis is a popular database language which has many applications in caching, messaging, and analytics. One of the most basic things you can do in Redis is set and define key value pairs. In this tutorial we'll be looking at how to do that, along with some other basic functionality which is useful.

Setting a key value pair in Redis

If you don't have redis installed, you can do that by following our tutorial here. After that, open a terminal window and run the following command:

shell Copy

Now we have activated redis-cli, we can set keys via the terminal. To do so, write the following and press enter:

shell Copy
set someKeyName someValue

The above code will set a new key with the value "someValue". Then, when we want to get the value of our key, we can simply type the following in terminal:

shell Copy
get someKeyName # returns "someValue"

Setting an integer

While still in redis-cli, we can set integers in the same way. We can also increase integers using the incr keyword. For example, below we set an integer called myInt to 11, and then increase it to one. The output is then 12.

shell Copy
set myInt 11 incr MyInt get MyInt # returns 12

Finding and Monitoring our Keys

Once we have a few keys in our redis database, we'll at some point probably want a list of them. In a new terminal window, you can get a list of all of them by running the following command:

shell Copy
redis-cli --scan

If we want to search our keys, we can use the --pattern terminal code. The below code will return any key starting with anything (indicated by the star) and in "Int".

shell Copy
redis-cli --scan --pattern '*Int'

Finally, we can monitor when keys are created or changed, by using the following command.

shell Copy
redis-cli monitor

Note that this will only track keys made after we initiate the monitor command.

Last Updated Saturday, 6 November 2021

Subscribe to Newsletter

Subscribe to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email