Search code examples
redispython-3.6

Python3/Redis: redis.exceptions.ResponseError: unknown command 'JSON.SET'


I'm trying to run the sample program from this RedisLabs page. I chose Option A - which was to set up the free Redis cloud server. (Seems like if you install manually, then you have to add the JSON as a plugin.) I'm able to connect and use other "set" commands, but getting error on JSON:

  File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\client.py", line 901, in execute_command
    return self.parse_response(conn, command_name, **options)
  File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\client.py", line 915, in parse_response
    response = connection.read_response()
  File "C:\Users\nwalt\.virtualenvs\TDAmeritradeGetQuotes\lib\site-packages\redis\connection.py", line 756, in read_response
    raise response
redis.exceptions.ResponseError: unknown command 'JSON.SET'

My Python test program (except put in the sample endpoint before posting):

    import redis
    import json
    import pprint
    
    host_info = "redis.us-east-1-1.ec2.cloud.redislabs.com"
    redisObj = redis.Redis(host=host_info, port=18274, password='xxx')
    
print ("Normal call to Redis")
redisObj.set('foo', 'bar')
value = redisObj.get('foo')
print(value)


capitals = {
     "Lebanon": "Beirut",
     "Norway": "Oslo",
     "France": "Paris"
 }
print ("capitals - before call to Redis")
pprint.pprint(capitals)


print("JSON call to Redis")
redisObj.execute_command('JSON.SET', 'doc', '.', json.dumps(capitals))
print("Data Saved, now fetch data back from redis")
reply = json.loads(redisObj.execute_command('JSON.GET', 'doc'))
print("reply from Redis get")
pprint.pprint(reply)

This is the screen shot from their website where I created the database. I didn't see any option to enable JSON or add any modules.

enter image description here


Solution

  • Not sure this was available when I created the REDIS database, but it is now. When you create it on redislabs.com, you can turn on the modules, and pick one from the list.

    enter image description here

    Then use this library: "rejson" from https://pypi.org/project/rejson/ to get the method "jsonset" method, using such code such as this:

    rj = Client(host=config_dict['REDIS_CONFIG_HOST'], port=config_dict['REDIS_CONFIG_PORT'],                      password=config_dict['REDIS_CONFIG_PASSWORD'], decode_responses=True)
    
    out_doc = {} 
    out_doc['firstname'] = "John"
    out_doc['lastname'] = "Doe"
    rj.jsonset('config', Path.rootPath(), out_doc)
    get_doc = rj.jsonget('config', Path.rootPath())
    pprint.pprint(get_doc)