How do you set a boolean value in Redis?

Viewed 4980

When I set a boolean value (true) to a key in Redis, the value is coerced to a string ("true"). With memcached, I get back what I put in. But with Redis it seems to stringify everything. I can't find any docs on how to fix this boolean issue. No special boolean_set methods or boolean options.

I'm using Ruby.

Example follows.

Set up:

require 'redis'
@redis = Redis.new

running in irb:

irb(main):034:0> bool = true
=> true
irb(main):035:0> bool
=> true
irb(main):036:0> @redis.set("example", bool)
=> "OK"
irb(main):037:0> @redis.get("example")
=> "true"
irb(main):038:0> @redis.get("example") == bool
=> false

1 Answers

"The Redis String type is the simplest type of value you can associate with a Redis key. It is the only data type in Memcached, so it is also very natural for newcomers to use it in Redis." - it's impossible to do in an "easy" way.

But regarding what for you need it, you can create some class to write/read of any type of data.

For example, how it's implementing in Rails ActiveRecord Cache

Some simple interpretation of this pretty big class with using of next Marshal's methods: dump and load

class RedisAnyTypesHandler
  def initialize(redis)
    @redis = redis
  end

  def write(key, value)
    @redis.set(key, serialize(value))
  end

  def read(key)
    deserialize(@redis.get(key))
  end

  private

  def serialize(value)
    Marshal.dump(value)
  end

  def deserialize(value)
    Marshal.load(value)
  end
end

Now you can play with any type of data:

> redis_handler = RedisAnyTypesHandler.new(@redis)
> bool = true
=> true
> redis_handler.write('example', bool)
=> "OK"
> redis_handler.read('example') == bool
=> true

> class Foo
>   attr_accessor :foo
> end
=> nil
> foo = Foo.new
=> #<Foo:0x0000556dc19097f8>
> foo.foo = 2
=> 2
> redis_handler.write('example_2', foo)
=> "OK"
> redis_handler.read('example_2').foo
=> 2
Related