redis: the complete guide to query types and modules (json, bloom, timeseries)

A comprehensive article covering Redis, its core query types, and advanced modules like RedisJSON, RedisBloom, and RedisTimeSeries.

redis: the complete guide to query types and modules (json, bloom, timeseries)

introduction

Redis is a high-performance, in-memory data store that has been widely used as ‘data storage and cache (and message broker) for its popularity; it supports multiple data structures and possesses dozens of commands.Besides its core, Redi offers powerful modules such as RedISJSON, the most advanced module on Redistons, redisBloom or ReditTimeSeries which extend to use with modern applications.

This article covers the core query types in Redis, as well as advanced querying with RediJSON, RedISBloom and RedixTimeSeries (with practical examples for each).


reactjs: basics and most-used examples

ReactJS is a JavaScript library for building user interfaces, and it has been described as one of the most common patterns and examples.

1. creating a functional component

1
2
3
function Welcome(props) {
  return <h1>Hello, {props.name}!</h1>;
}

2. using state with hooks

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

3. passing props

1
2
3
4
5
6
7
function Greeting({ name }) {
  return <p>Hello, {name}!</p>;
}

function App() {
  return <Greeting name="Alice" />;
}

4. handling events

1
2
3
4
5
6
function Button() {
  function handleClick() {
    alert('Button clicked!');
  }
  return <button onClick={handleClick}>Click Me</button>;
}

5. conditional rendering

1
2
3
4
5
6
7
function UserStatus({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>}
    </div>
  );
}

state management in react: redux, redux toolkit, and modern alternatives

It can be difficult to understand how to manage state in large React applications. Here are the most popular tools and modern alternatives.

redux

Redux is a standard state container for JavaScript apps, often used with React to manage global state.

  • Key Features:
    • Centralized state management
    • Predictable state updates via actions and reducers
    • DevTools for time-travel debugging
  • Usage Example:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    import { createStore } from 'redux';
    
    function counter(state = 0, action) {
      switch (action.type) {
        case 'INCREMENT':
          return state + 1;
        case 'DECREMENT':
          return state - 1;
        default:
          return state;
      }
    }
    
    const store = createStore(counter);
    store.dispatch({ type: 'INCREMENT' });
    

redux toolkit

The official, recommended method of writing Redux logic is Redx Toolkit (the formal, suggested way to write Redix logic) which simplifies Redlox code and reduces boilerplate.

  • Key Features:
    • Simplified setup and configuration
    • Built-in utilities for reducers, actions, and async logic
    • Encourages best practices
  • Usage Example:
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    
    import { configureStore, createSlice } from '@reduxjs/toolkit';
    
    const counterSlice = createSlice({
      name: 'counter',
      initialState: 0,
      reducers: {
        increment: state => state + 1,
        decrement: state => state - 1,
      },
    });
    
    const store = configureStore({
      reducer: counterSlice.reducer,
    });
    
    store.dispatch(counterSlice.actions.increment());
    

modern alternatives

  • React Context API: Built-in solution for passing state deeply without prop drilling. Great for small to medium apps.
  • Zustand: Minimal, scalable state management with a simple API and no boilerplate.
  • Jotai: Primitive and flexible state management using atoms.
  • Recoil: Experimental state management library from Facebook, designed for complex state graphs.

Choosing a Tool:

  • Use Redux Toolkit for large, complex apps needing global state and advanced debugging.
  • Use Context API, Zustand, or Jotai for simpler or more modern React projects.

react frameworks: next.js, remix, and gatsby

Often powerful frameworks such as server-side rendering, static site generation, routing and more are often used to enhance the development of Modern React. Here’s a closer look at the most popular ones.

next.js

The Vercel-developed production-grade React framework, Next.js is a product-level Reaction framework developed by Vercell that allows developers to build fast, efficient web applications with low configuration and minimal implementation.

  • Key Features:
    • Hybrid rendering: supports static generation (SSG), server-side rendering (SSR), and client-side rendering (CSR)
    • File-based routing system
    • API routes for backend logic
    • Built-in image optimization and performance enhancements
    • Incremental Static Regeneration (ISR) for updating static content after deployment
    • Middleware and edge functions for advanced use cases
  • Use Cases:
    • SEO-friendly websites and blogs
    • E-commerce platforms
    • Dashboards and SaaS products
    • Hybrid apps that need both static and dynamic content

remix

Remix is a full-stack React framework focused on web standards, fast data loading and seamless developer experience that emphasizes web standard architecture as well as the development of Web applications.

  • Key Features:
    • Nested routes and layouts for complex UIs
    • Data loading at the route level (loaders and actions)
    • Built-in support for forms and mutations
    • Server-side rendering by default, with progressive enhancement
    • Works with any backend (Node.js, serverless, edge, etc.)
    • Emphasis on accessibility and web fundamentals
  • Use Cases:
    • Complex, data-driven web apps
    • Applications requiring fine-grained control over data fetching and mutations
    • Projects where web standards and performance are a priority

gatsby

The Gatsby is a React-based static site generator for speed and content-rich sites, which has been designed to be an efficient solution.

  • Key Features:
    • Static site generation (SSG) for ultra-fast performance
    • GraphQL data layer to source content from CMSs, APIs, files, and more
    • Huge plugin ecosystem for images, SEO, analytics, and integrations
    • Built-in code splitting and image optimization
    • Progressive Web App (PWA) support
  • Use Cases:
    • Blogs, documentation, and marketing sites
    • Content-heavy websites with data from multiple sources
    • Sites where build-time rendering and performance are critical

1. core redis query types

Redis supports a number of data structures, each with its own set of commands (queries) and many other data structure.

1.1. strings

  • SET/GET: Store and retrieve string values.
    1
    2
    
    SET key "value"
    GET key
    
  • INCR/DECR: Increment or decrement numeric values.
    1
    2
    
    INCR counter
    DECR counter
    

1.2. hashes

  • HSET/HGET: Store and retrieve field-value pairs.
    1
    2
    3
    
    HSET user:1 name "Alice" age 30
    HGET user:1 name
    HGETALL user:1
    

1.3. lists

  • LPUSH/RPUSH/LPOP/RPOP: Add/remove elements from lists.
    1
    2
    3
    4
    
    LPUSH tasks "task1"
    RPUSH tasks "task2"
    LPOP tasks
    RPOP tasks
    

1.4. sets

  • SADD/SREM/SMEMBERS: Add/remove members, get all members.
    1
    2
    3
    
    SADD tags "redis" "database"
    SREM tags "database"
    SMEMBERS tags
    

1.5. sorted sets

  • ZADD/ZRANGE/ZREM: Add members with scores, get ranges, remove members.
    1
    2
    3
    
    ZADD leaderboard 100 "Alice" 200 "Bob"
    ZRANGE leaderboard 0 -1 WITHSCORES
    ZREM leaderboard "Alice"
    

1.6. key queries

  • EXISTS/DEL/SCAN: Check existence, delete, or scan keys.
    1
    2
    3
    
    EXISTS key
    DEL key
    SCAN 0 MATCH user:*
    

2. redisjson: storing and querying json documents

RedisJSON is a Redi module for storage, updating and querying JSON documents natively (e.g.

2.1. basic commands

  • JSON.SET/JSON.GET: Store and retrieve JSON documents.
    1
    2
    
    JSON.SET user:1 $ '{"name": "Alice", "age": 30}'
    JSON.GET user:1
    

2.2. path queries

  • Query specific fields using JSONPath:
    1
    2
    
    JSON.GET user:1 $.name
    JSON.GET user:1 $.age
    

2.3. updating and deleting

  • Update fields:
    1
    
    JSON.SET user:1 $.age 31
    
  • Delete fields:
    1
    
    JSON.DEL user:1 $.age
    

2.4. searching with redisearch (with redisjson)

  • Index and search JSON documents:
    1
    2
    
    FT.CREATE idx:users ON JSON SCHEMA $.name AS name TEXT $.age AS age NUMERIC
    FT.SEARCH idx:users "@name:Alice"
    

3. redisbloom: probabilistic data structures

RedisBloom adds scalable probabilistic data structures for fast set membership, counting and more to the list of rapidly scheduled members as well as other systems such as redisbloom.

3.1. bloom filter

  • BF.ADD/BF.EXISTS: Add and check existence (with possible false positives).
    1
    2
    
    BF.ADD emails "alice@example.com"
    BF.EXISTS emails "alice@example.com"
    

3.2. cuckoo filter

  • CF.ADD/CF.EXISTS: Similar to Bloom, but supports deletion.
    1
    2
    
    CF.ADD users "user1"
    CF.EXISTS users "user1"
    

3.3. count-min sketch

  • CMS.INCRBY/CMS.QUERY: Count occurrences of items.
    1
    2
    
    CMS.INCRBY pageviews "page1" 1
    CMS.QUERY pageviews "page1"
    

3.4. top-k

  • TOPK.ADD/TOPK.LIST: Track most frequent items.
    1
    2
    3
    
    TOPK.RESERVE topk 3 2000 7 0.925
    TOPK.ADD topk "apple" "banana" "apple"
    TOPK.LIST topk
    

4. redistimeseries: time series data

The RedisTimeSeries module is a useful example of storing and querying time series data efficiently.

4.1. creating and adding data

  • TS.CREATE/TS.ADD: Create a time series and add data points.
    1
    2
    
    TS.CREATE temperature:room1
    TS.ADD temperature:room1 * 22.5
    

4.2. range queries

  • TS.RANGE: Query data points in a time range.
    1
    2
    
    TS.RANGE temperature:room1 - +
    TS.RANGE temperature:room1 1620000000000 1620003600000
    

4.3. aggregations

  • TS.RANGE with aggregation:
    1
    
    TS.RANGE temperature:room1 - + AGGREGATION avg 60000
    

4.4. multi-series queries

  • TS.MRANGE: Query multiple time series by label.
    1
    
    TS.MRANGE - + FILTER room=1
    

5. best practices and use cases

  • Use Redis core for caching, session storage, leaderboards, and pub/sub.
  • Use RedisJSON for document storage and flexible querying.
  • Use RedisBloom for fast set membership, deduplication, and analytics.
  • Use RedisTimeSeries for IoT, monitoring, and time series analytics.
  • Consider Memcached for Simplicity and Performance:
    • Memcached is a lightweight, high-performance, in-memory key-value store designed primarily for simple caching use cases.
    • If you only need basic key-value caching without advanced data structures, persistence, or modules, Memcached can be easier to operate and may offer lower latency and resource usage than Redis.
    • Memcached is often preferred for straightforward cache scenarios where simplicity and raw speed are more important than Redis’s rich feature set.

6. resources


conclusion

Redis is an extensible and powerful data platform, which can be built by learning its core queries and advanced modules to build fast, scalable and feature-rich applications for a wide range of use cases.


Built with Hugo
Theme Stack designed by Jimmy