Working with Numeric Operations in Redis Using Go

Working with Numeric Operations in Redis Using Go

Welcome back! Now that you've learned how to work with numbers in Redis using Go, it's time to expand that knowledge and explore some basic operations with these numbers. This lesson will show you how to perform operations such as incrementing, decrementing, and modifying numeric values directly in Redis using Go.

What You'll Learn

In this lesson, you will learn how to:

  1. Increment and decrement numeric values.
  2. Modify numeric values using operations such as increments by a floating point.

Here's the code snippet that we'll be working with:

package main

import (
    "fmt"
    "github.com/redis/go-redis/v9"
    "context"
)

func main() {
    ctx := context.Background()

    // Connect to Redis
    rdb := redis.NewClient(&redis.Options{
        Addr: "localhost:6379",
        DB:   0, // use default DB
    })

    // Setting and getting string values
    rdb.Set(ctx, "count", 5, 0)
    rdb.Set(ctx, "completion_rate", 95.5, 0)
    rdb.Set(ctx, "duration", 0, 0) // Ensure 'duration' is set initially

    rdb.Decr(ctx, "count")
    rdb.IncrByFloat(ctx, "completion_rate", 1.5)
    rdb.Incr(ctx, "duration")

    count, _ := rdb.Get(ctx, "count").Int()
    completionRate, _ := rdb.Get(ctx, "completion_rate").Float64()
    duration, _ := rdb.Get(ctx, "duration").Int()

    fmt.Printf("Course count: %d\n", count) // Course count: 4
    fmt.Printf("Completion rate: %f\n", completionRate) // Completion rate: 97.000000
    fmt.Printf("Duration: %d\n", duration) // Duration: 1
}

Let's break it down:

  • After setting initial values for count, completion_rate, and duration, we perform various operations:
    • Decr(ctx, "count") decreases the value of count by 1. You can also use the DecrBy method to decrement by a specific value: DecrBy(ctx, "count", 2) will decrement count by 2. Note that Decr can only be used on integer values.
    • IncrByFloat(ctx, "completion_rate", 1.5) increments completion_rate by 1.5. Note that this function can be used on both integer and floating-point values.
    • Incr(ctx, "duration") increases the duration by 1. You can also use the IncrBy method to increment by a specific value: IncrBy(ctx, "duration", 5) will increment duration by 5. Note that Incr can only be used on integer values.
  • Finally, we retrieve the values to display the updated state.

Atomicity and Numeric Operations in Redis Using Go

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal