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.
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
listof values retrieved as a single set. To apply element-wise, this will need to be run via something likeVectorize.- missing
What to substitute into the returned vector for missing elements. By default an NA will be added. A
stopexpression is OK and will only be evaluated if values are missing.
Examples
# 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")
#> [1] 1
r$HSET(key, "b", "banana")
#> [1] 1
r$HSET(key, "c", "carrot")
#> [1] 1
# Now we have a hash with three elements:
r$HGETALL(key)
#> [[1]]
#> [1] "a"
#>
#> [[2]]
#> [1] "apple"
#>
#> [[3]]
#> [1] "b"
#>
#> [[4]]
#> [1] "banana"
#>
#> [[5]]
#> [1] "c"
#>
#> [[6]]
#> [1] "carrot"
#>
# Ew, that's not very nice. This is nicer:
redux::from_redis_hash(r, key)
#> a b c
#> "apple" "banana" "carrot"
# 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)
#> $a
#> [1] "apple"
#>
#> $b
#> [1] "banana"
#>
#> $c
#> [1] "carrot"
#>
# To get just some elements:
redux::from_redis_hash(r, key, c("a", "c"))
#> a c
#> "apple" "carrot"
# And if some are not present:
redux::from_redis_hash(r, key, c("a", "x"))
#> a x
#> "apple" NA
redux::from_redis_hash(r, key, c("a", "z"), missing = "zebra")
#> a z
#> "apple" "zebra"
r$DEL(key)
#> [1] 1