TOC

RedisJSON 体验

相关阅读:Redis 拓展模块,其中用 RedisJSON 举例编译安装。

简单示例 (GET / SET):

127.0.0.1:6379> json.set abc . 123
OK
127.0.0.1:6379> json.get abc .
"123"
127.0.0.1:6379> json.set xyz . '{"a": 1, "b": true, "c": [{"name": "foo"}, {"name": "bar"}]}'
OK
json.get xyz .c[0]
"{\"name\":\"foo\"}"
127.0.0.1:6379> json.set xyz .a 2
OK
127.0.0.1:6379> json.get xyz .c[0].name
"\"foo\""
127.0.0.1:6379> json.set xyz .c[0].name '"loong"'
OK
127.0.0.1:6379> json.get xyz .a .c[0].name
"{\".c[0].name\":\"loong\",\".a\":2}"

Json 路径语法

现在还没有相关行业标准,RedisJSON 自己实现了一套(v1), 后来参考 JSONPath 语法又重新实现了一遍 (v2)。
至于 v1 和 v2 有什么区分,就不用深究了。

大致知道这样可以就行了:

.store.book[0].title
// 相当于 `V['store']['book'][0]['title']`

拓展命令

  1. JSON.ARRAPPEND arrappend
  2. JSON.ARRINDEX arrindex
  3. JSON.ARRINSERT arrinsert
  4. JSON.ARRLEN arrlen
  5. JSON.ARRPOP arrpop
  6. JSON.ARRTRIM arrtrim
  7. JSON.CLEAR clear
  8. JSON.DEBUG debug
  9. JSON.DEL delete
  10. JSON.GET get / jsonget
  11. JSON.MGET mget / jsonmget
  12. JSON.NUMINCRBY numincrby
  13. JSON.NUMMULTBY nummultby img
  14. JSON.OBJKEYS objkeys
  15. JSON.OBJLEN objlen
  16. JSON.RESP resp
  17. JSON.SET set / jsonset
  18. JSON.STRAPPEND strappend
  19. JSON.STRLEN strlen
  20. JSON.TOGGLE toggle
  21. JSON.TYPE type

Python 库还有以下两个方法:

  1. set_file(name, path, file_name, nx=False, xx=False, decode_keys=False)
    return self.set(name, path, file_content, nx=nx, xx=xx, decode_keys=decode_keys)
    
    1. set_path(json_path, root_folder, nx=False, xx=False, decode_keys=False)
    遍历 root_folder 得到 file_path, file_name (file_path.split('.', 1)[0])
    然后调用 set_file(file_name, json_path, file_path, nx=nx, xx=xx, decode_keys=decode_keys)

使用(Python)

Python 最知名的 Redis 客户端库 redis-py 已经支持 RedisJSON 拓展指令。

import redis
from redis.commands.json import JSON

r = redis.Redis(host='localhost', port=6379, db=0)
jr = JSON(r)

jr.set('foo', '.', {"a": 1, "b": True, "c": [{"name": "foo"}, {"name": "bar"}]})

jr.numincrby('foo', 'a', 1)

jr.toggle('foo', '.b') # only works for booleans

jr.arrappend('foo', '.c', {"name": "air"})

print(jr.get('foo', '.'))
# {'a': 2, 'b': False, 'c': [{'name': 'foo'}, {'name': 'bar'}, {'name': 'air'}]}

print(jr.get('foo', '.c[-1].name'))
# air

就缺搜索了,如果加上 RediSearch,就完美了。
PS: RediSearch 的新版本已经优化了对 JSON 的支持。

参考资料与拓展阅读