Skip to main content
Version: 2.x

Strings

Strings are the simplest Redis value: a byte sequence that can hold text, a number or an encoded case class. This page lists every string command on the Redis service, grouped by purpose, with the option types they take.

Reading and Writing Valuesโ€‹

The basic commands read and write one key at a time. Methods that return user data, such as Redis#get, finish with returning[A], as explained in Getting Started:

CommandResultDescription
Redis#getOption[A]Returns the value of a key, or None when it does not exist
Redis#getDelOption[A]Returns the value of a key and deletes the key
Redis#getSetOption[A]Sets a new value and returns the old one
Redis#setBooleanSets a value, with optional expiry and condition
Redis#setGetOption[V]Like set, and returns the old value in the same call
Redis#setNxBooleanSets a value only when the key does not exist
Redis#appendLongAppends to a value and returns the new length
Redis#strLenLongReturns the length of a value
Redis#getRangeOption[A]Returns the substring selected by a Scala Range
Redis#setRangeLongOverwrites part of a value from an offset

To write a value and read it back:

import zio._
import zio.redis._

def readWrite(redis: Redis): IO[RedisError, Option[String]] =
for {
_ <- redis.set("greeting", "hello")
_ <- redis.append("greeting", ", world")
value <- redis.get("greeting").returning[String]
} yield value

Redis#getSet and Redis#getDel return the previous value through returning, while Redis#setGet fixes the result type to the value type V. To replace a value and keep the old one:

import zio._
import zio.redis._

def swap(redis: Redis): IO[RedisError, Option[String]] =
redis.setGet("token", "new-token")

Conditional Writes and Expiryโ€‹

Redis#set and Redis#setGet share the same optional parameters:

ParameterTypeEffect
expireTimeOption[Duration]Sets a time to live, sent to Redis in milliseconds
updateOption[Update]Sets the key only if it exists or only if it is missing
keepTtlOption[KeepTtl]Keeps the time to live the key already has

Update has four cases. Update.SetExisting sends XX and Update.SetNew sends NX. The remaining cases, Update.SetLessThan and Update.SetGreaterThan, are shared with other commands and are not valid for SET. KeepTtl is a single case object.

Redis#set returns false when the condition prevents the write. To store a value only if the key is missing, and keep it for ten minutes:

import zio._
import zio.redis._

def acquire(redis: Redis): IO[RedisError, Boolean] =
redis.set("lock:job", "owner-1", Some(10.minutes), Some(Update.SetNew))

To overwrite a value without touching its expiry:

import zio._
import zio.redis._

def refresh(redis: Redis): IO[RedisError, Boolean] =
redis.set("session", "v2", keepTtl = Some(KeepTtl))

Dedicated commands combine a write with an expiry in one call:

CommandResultDescription
Redis#setExUnitSets a value that expires after a Duration
Redis#pSetExUnitSets a value that expires after a Duration, in ms
Redis#setNxBooleanSets a value only when the key does not exist

Reading with an Expiryโ€‹

Redis#getEx reads a value and changes its time to live in one step. It has three overloads:

OverloadEffect
getEx(key, expire, expireTime)Sets a relative expiry with an Expire and Duration
getEx(key, expiredAt, timestamp)Sets an absolute expiry with an ExpiredAt and Instant
getEx(key, persist)Removes the expiry when persist is true

Expire selects the unit of the relative form: Expire.SetExpireSeconds sends EX and Expire.SetExpireMilliseconds sends PX. ExpiredAt does the same for the absolute form: ExpiredAt.SetExpireAtSeconds sends EXAT and ExpiredAt.SetExpireAtMilliseconds sends PXAT.

To read a value and extend its lifetime, then read it and make it permanent:

import zio._
import zio.redis._

def touchAndPersist(redis: Redis): IO[RedisError, Option[String]] =
for {
_ <- redis.getEx("session", Expire.SetExpireSeconds, 30.minutes).returning[String]
value <- redis.getEx("session", persist = true).returning[String]
} yield value

Multiple Keysโ€‹

The multi-key commands take at least one key or pair, followed by any number of extra ones:

CommandResultDescription
Redis#mGetChunk[Option[A]]Returns the values of several keys
Redis#mSetUnitSets several key-value pairs at once
Redis#mSetNxBooleanSets all pairs only if none of the keys exist

Redis#mGet returns one entry per key, in order, with None for missing keys. To set two keys and read them back:

import zio._
import zio.redis._

def multi(redis: Redis): IO[RedisError, Chunk[Option[String]]] =
for {
_ <- redis.mSet("a" -> "1", "b" -> "2")
values <- redis.mGet("a", "b", "missing").returning[String]
} yield values

Countersโ€‹

Counters treat a value as a 64-bit integer, or as a float for Redis#incrByFloat. Redis creates a missing key with the value 0 before applying the change:

CommandResultDescription
Redis#incrLongAdds one and returns the new value
Redis#incrByLongAdds a Long and returns the new value
Redis#incrByFloatDoubleAdds a Double and returns the new value
Redis#decrLongSubtracts one and returns the new value
Redis#decrByLongSubtracts a Long and returns the new value

To count page views and add a fractional score:

import zio._
import zio.redis._

def counters(redis: Redis): IO[RedisError, (Long, Double)] =
for {
views <- redis.incr("page:views")
score <- redis.incrByFloat("page:score", 1.5)
} yield (views, score)

Bit Operationsโ€‹

Bit commands treat a string as an array of bits. getBit and setBit address one bit by its offset:

CommandResultDescription
Redis#getBitLongReturns the bit at an offset
Redis#setBitBooleanSets or clears the bit at an offset, returns the old bit
Redis#bitCountLongCounts bits set to 1, optionally within a Range
Redis#bitPosLongFinds the first set or cleared bit, optionally in a BitPosRange
Redis#bitOpLongApplies a BitOperation to source keys and stores the result
Redis#bitFieldChunk[Option[Long]]Runs one or more BitFieldCommand values

BitOperation has the cases AND, OR, XOR and NOT. BitPosRange(start, end) takes a start offset and an optional end offset.

To track daily visits per user and combine two days:

import zio._
import zio.redis._

def visits(redis: Redis): IO[RedisError, Long] =
for {
_ <- redis.setBit("visits:mon", 7L, value = true)
_ <- redis.setBit("visits:tue", 7L, value = true)
_ <- redis.bitOp(BitOperation.AND, "visits:both", "visits:mon", "visits:tue")
count <- redis.bitCount("visits:both")
} yield count

Redis#bitCount accepts a Scala Range, and Redis#bitPos accepts a BitPosRange. To restrict both to the first bytes of a key:

import zio._
import zio.redis._

def inFirstBytes(redis: Redis): IO[RedisError, (Long, Long)] =
for {
ones <- redis.bitCount("flags", Some(0 to 3))
first <- redis.bitPos("flags", bit = true, Some(BitPosRange(0L, Some(3L))))
} yield (ones, first)

Bit Fieldsโ€‹

Redis#bitField treats a string as a sequence of integers of any width. It takes one BitFieldCommand and any number of further ones, and returns one Option[Long] per command:

TypeFieldsDescription
BitFieldCommand.BitFieldGettype, offsetReads an integer
BitFieldCommand.BitFieldSettype, offset, valueWrites an integer
BitFieldCommand.BitFieldIncrtype, offset, incrementAdds to an integer
BitFieldCommand.BitFieldOverflowFail, Sat, WrapSelects overflow behavior for later commands

The integer type is a BitFieldType, either BitFieldType.UnsignedInt(size) or BitFieldType.SignedInt(size). To write and increment an unsigned 8-bit counter with saturating overflow:

import zio._
import zio.redis._
import zio.redis.BitFieldCommand._

def bitFields(redis: Redis): IO[RedisError, Chunk[Option[Long]]] =
redis.bitField(
"counters",
BitFieldSet(BitFieldType.UnsignedInt(8), 0, 250L),
BitFieldOverflow.Sat,
BitFieldIncr(BitFieldType.UnsignedInt(8), 0, 10L)
)

Longest Common Subsequenceโ€‹

Redis#lcs compares the values of two keys. It takes an optional LcsQueryType and returns an Lcs:

LcsQueryTypeResult
noneLcs.PlainLcs(lcs) with the common subsequence
LcsQueryType.LenLcs.Length(length) with its length
LcsQueryType.Idx(minMatchLength, withMatchLength)Lcs.Matches(matches, length) with match ranges

Each Match holds two MatchIdx(start, end) ranges and, when withMatchLength is set, a matchLength. minMatchLength defaults to 1 and withMatchLength to false. To print the length of the shared text:

import zio._
import zio.redis._

def commonLength(redis: Redis): IO[RedisError, Long] =
redis.lcs("key1", "key2", Some(LcsQueryType.Len)).map {
case Lcs.Length(length) => length
case Lcs.PlainLcs(lcs) => lcs.length.toLong
case Lcs.Matches(_, size) => size
}

ZIO Chat

๐Ÿ”ฅ Ignite your ZIO journey with ZIO Chat! ๐Ÿ”ฅ Ready to unravel the intricacies of ZIO? As your trusty sidekick, I'm here to light the way. No matter if you're wandering through functional forests or traversing effectful landscapes, I've got answers to keep you on track. Your ZIO adventure starts here โ€“ ask me anything and let's explore together!