Let’s say you want to utilize redis to store and manipulate this JSON
{
"name": "Garfield",
"traits": {
"lazy": true,
"hungry": true,
"sassy": true,
"loves_lasagna": true,
"hates_mondays": true
}
}
Code language: JSON / JSON with Comments (json)
You can use the module RedisJSON to do it.
Prerequisites
If you don’t have the module installed you must build it first.
You’ll need to install these first (example commands are for Rocky Linux, but should be at least similar to other distros)
- gcc
dnf install gcc
- clang
dnf install clang-devel clang-libs
- git
dnf install git
The build process is
Install Cargo
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Code language: JavaScript (javascript)
Load the Cargo environment
source "$HOME/.cargo/env"
Code language: JavaScript (javascript)
Get the RedisJSON source from https://github.com/RedisJSON/RedisJSON
git clone https://github.com/RedisJSON/RedisJSON.git
Code language: PHP (php)
Go into the RedisJSON source directory
cd RedisJSON
Build it using Cargo
cargo build --release
You’ll find the built module in the directory /target/release/ with the name librejson.so
Create a directory for the modules
mkdir /etc/redis/modules
Copy the module to the newly created directory. Assuming you’re in RedisJSON source directory the command is
cp /target/release/librejson.so /etc/redis/modules/
Edit the configuration so Redis load the new module
vim /etc/redis/redis.conf
################################## MODULES #####################################
# Load modules at startup. If the server is not able to load modules
# it will abort. It is possible to use multiple loadmodule directives.
#
# loadmodule /path/to/my_module.so
# loadmodule /path/to/other_module.so
<strong>loadmodule /etc/redis/modules/librejson.so</strong>
Code language: PHP (php)
Restart your Redis service. If you’re using sentinel or cluster, its safer to do this after the module is installed in all of the nodes.
service redis restart
Play with the RedisJSON module
After installation you can then use the commands in redis-cli or any suppored library.
Example using redis-cli
Insert the JSON
JSON.SET animal:garfield $ ’ { "name": "Garfield", "traits": { "lazy": true, "hungry": true, "sassy": true, "loves_lasagna": true, "hates_mondays": true } }’
Code language: JavaScript (javascript)
Get Garfield’s traits
JSON.GET animal:Garfield $.traits
Code language: JavaScript (javascript)
Get the value of whether Garfield is lazy or not
JSON.GET animal:Garfield $.traits.lazy
Code language: JavaScript (javascript)
Additional note
The maximum depth of the JSON object is 128
Leave a Reply