Convert a Redis hash to a character vector or list. This tries to bridge the gap between the way Redis returns hashes and the way that they are nice to work with in R, but keeping all conversions very explicit.

from_redis_hash(
  con,
  key,
  fields = NULL,
  f = as.character,
  missing = NA_character_
)

Arguments

con

A Redis connection object

key

key of the hash

fields

Optional vector of fields (if absent, all fields are retrieved via HGETALL.

f

Function to apply to the list of values retrieved as a single set. To apply element-wise, this will need to be run via something like Vectorize.

missing

What to substitute into the returned vector for missing elements. By default an NA will be added. A stop expression is OK and will only be evaluated if values are missing.

Examples

if (redux::redis_available()) {
  # Using a random key so we don't overwrite anything in your database:
  key <- paste0("redux::", paste(sample(letters, 15), collapse = ""))
  r <- redux::hiredis()
  r$HSET(key, "a", "apple")
  r$HSET(key, "b", "banana")
  r$HSET(key, "c", "carrot")

  # Now we have a hash with three elements:
  r$HGETALL(key)

  # Ew, that's not very nice.  This is nicer:
  redux::from_redis_hash(r, key)

  # If one of the elements was not a string, then that would not
  # have worked, but you can always leave as a list:
  redux::from_redis_hash(r, key, f = identity)

  # To get just some elements:
  redux::from_redis_hash(r, key, c("a", "c"))

  # And if some are not present:
  redux::from_redis_hash(r, key, c("a", "x"))
  redux::from_redis_hash(r, key, c("a", "z"), missing = "zebra")

  r$DEL(key)
}
#> [1] 1