相关阅读: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']`
拓展命令
- JSON.ARRAPPEND
arrappend
- JSON.ARRINDEX
arrindex
- JSON.ARRINSERT
arrinsert
- JSON.ARRLEN
arrlen
- JSON.ARRPOP
arrpop
- JSON.ARRTRIM
arrtrim
- JSON.CLEAR
clear
- JSON.DEBUG
debug
- JSON.DEL
delete
- JSON.GET
get
/jsonget
- JSON.MGET
mget
/jsonmget
- JSON.NUMINCRBY
numincrby
- JSON.NUMMULTBY
nummultby
- JSON.OBJKEYS
objkeys
- JSON.OBJLEN
objlen
- JSON.RESP
resp
- JSON.SET
set
/jsonset
- JSON.STRAPPEND
strappend
- JSON.STRLEN
strlen
- JSON.TOGGLE
toggle
- JSON.TYPE
type
Python 库还有以下两个方法:
set_file(name, path, file_name, nx=False, xx=False, decode_keys=False)
1.return self.set(name, path, file_content, nx=nx, xx=xx, decode_keys=decode_keys)
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 的支持。
参考资料与拓展阅读
- Redis, RedisJSON: Public Preview & Performance Benchmarking
- Redis, Indexing, Querying, and Full-Text Search of JSON Documents with Redis
- Redis, Indexing JSON document using RediSearch
- Redis, RedisJSON - a JSON data type for Redis
- Redis, RediSearch - Redis Secondary Index & Query Engine
- OSChina, 开源资讯, RediSearch v2.2.5 发布,Redis 高性能全文搜索引擎
- RedisJson 横空出世,这性能杀疯了!