Основы RedisJSON и RedisGraph
Изучите хранение и запросы к документам JSON, а также использование возможностей графовой базы данных в Redis.
«Основы RedisJSON и RedisGraph» — бесплатный урок Redis Caching & Messaging (Pub/Sub, Streams) на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Redis Caching & Messaging (Pub/Sub, Streams), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Redis Caching & Messaging (Pub/Sub, Streams) содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Unlock New Data Types
Redis is incredibly versatile, but sometimes you need more specialized data handling. That's where Redis Modules come in!
These modules extend Redis's core functionality, allowing it to act as a document database, a graph database, and much more.
Introducing RedisJSON
RedisJSON is a module that lets you store, update, and retrieve JSON documents directly within Redis. This is great for managing semi-structured data like user profiles, product catalogs, or configuration settings.
- Native JSON support: Store complex JSON objects.
- Atomic operations: Update parts of a JSON document efficiently.
- Powerful querying: Retrieve data using JSONPath expressions.
Storing JSON with JSON.SET
To store a JSON document, we use the JSON.SET command. You provide a key, a path (usually $ for the root), and the JSON string.
Try adding a simple user profile:
JSON.SET user:profile:1 $ '{"name": "Emma", "age": 28, "city": "London"}'Retrieving JSON with JSON.GET
The JSON.GET command retrieves your JSON. You can get the entire document or specify a JSONPath to fetch only specific fields.
Let's get the full profile and then just Emma's name:
JSON.GET user:profile:1
JSON.GET user:profile:1 $.nameUpdating JSON Fields
One of RedisJSON's strengths is updating specific parts of a document without fetching and rewriting the whole thing. Use JSON.SET with a precise path.
Update Emma's age and add a new hobby:
JSON.SET user:profile:1 $.age 29
JSON.SET user:profile:1 $.hobbies '["reading", "hiking"]'
JSON.GET user:profile:1Introducing RedisGraph
RedisGraph is another powerful module that turns Redis into a graph database. Graph databases are excellent for modeling relationships between data, like social networks, recommendation engines, or fraud detection.
Instead of tables, you work with nodes (entities) and edges (relationships).
Graph Concepts
In RedisGraph, you'll use Cypher, a declarative graph query language, to interact with your data.
- Nodes: Represent entities (e.g., Person, Product).
- Labels: Categorize nodes (e.g.,
:Person). - Properties: Attributes of nodes/edges (e.g.,
name: 'Bob'). - Edges: Represent relationships (e.g.,
-[:FRIENDS_WITH]->).
Creating Graph Data
The GRAPH.QUERY command lets you execute Cypher queries. Let's create a simple social graph with two people and a 'FRIENDS_WITH' relationship.
Notice the graph name 'social' is used to identify our graph.
GRAPH.QUERY social "CREATE (:Person {name: 'Liam'})-[:FRIENDS_WITH]->(:Person {name: 'Olivia'})"Querying Graph Relationships
You can query the graph to find patterns and relationships. The MATCH clause finds the pattern, and RETURN specifies what data to retrieve.
Find who Liam is friends with:
GRAPH.QUERY social "MATCH (p:Person {name: 'Liam'})-[:FRIENDS_WITH]->(f:Person) RETURN p.name, f.name"RedisJSON Path Challenge
You have a RedisJSON document stored under the key product:details:123. The document looks like this:
{
"name": "Wireless Earbuds",
"specs": {
"color": "Black",
"battery_life": "8 hours",
"features": ["Noise Cancelling", "Waterproof"]
}
}Which command correctly retrieves the 'Noise Cancelling' feature?
Recap: JSON & Graphs
You've explored how RedisJSON enables efficient storage and manipulation of JSON documents using commands like JSON.SET and JSON.GET with JSONPath.
You also learned about RedisGraph, a powerful module for building and querying graph structures using Cypher, perfect for modeling relationships between data.
These modules significantly expand Redis's capabilities, letting it tackle a broader range of data modeling challenges!
Часто задаваемые вопросы
Урок «Основы RedisJSON и RedisGraph» бесплатный?
Да — полный текст урока «Основы RedisJSON и RedisGraph» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Redis Caching & Messaging (Pub/Sub, Streams), подпишись на CoddyKit PRO. Курс Redis Caching & Messaging (Pub/Sub, Streams) содержит 4 уроков всего.
Чему я научусь в уроке «Основы RedisJSON и RedisGraph»?
Изучите хранение и запросы к документам JSON, а также использование возможностей графовой базы данных в Redis. Ты практикуешь Redis Caching & Messaging (Pub/Sub, Streams) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Redis Caching & Messaging (Pub/Sub, Streams)?
Предыдущий опыт не требуется. Redis Caching & Messaging (Pub/Sub, Streams) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Основы RedisJSON и RedisGraph»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Redis Caching & Messaging (Pub/Sub, Streams)?
Да. Каждый урок Redis Caching & Messaging (Pub/Sub, Streams) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Обзор модулей Redis
- RediSearch для полнотекстового поиска
- Основы RedisJSON и RedisGraph
- Временные ряды с RedisTimeSeries