路径
访问JSON文档中的特定元素
路径允许您访问JSON文档中的特定元素。由于不存在JSON路径语法的标准,Redis JSON实现了自己的语法。JSON的语法基于常见的最佳实践,并有意模仿JSONPath。
JSON 支持两种查询语法:JSONPath 语法和第一版 JSON 中的旧路径语法。
JSON 根据路径查询的第一个字符知道使用哪种语法。如果查询以字符 $
开头,则使用 JSONPath 语法。否则,默认使用旧版路径语法。
返回的值是一个JSON字符串,其中包含一个顶层的JSON序列化字符串数组。 如果使用了多路径,则返回值是一个JSON字符串,其中包含一个顶层对象,该对象的值是序列化JSON值的数组。
JSONPath 支持
RedisJSON v2.0 引入了 JSONPath 支持。它遵循 Goessner 在他的 文章 中描述的语法。
JSONPath 查询可以解析 JSON 文档中的多个位置。在这种情况下,JSON 命令将操作应用于每个可能的位置。这是对 legacy path 查询的重大改进,后者仅对第一个路径进行操作。
请注意,使用JSONPath时,命令响应的结构通常会有所不同。有关更多详细信息,请参阅Commands页面。
新语法支持括号表示法,允许在键名中使用特殊字符,如冒号“:”或空格。
如果你想在CLI的查询中包含双引号,请将JSONPath用单引号括起来。例如:
JSON.GET store '$.inventory["mountain_bikes"]'
JSONPath 语法
以下JSONPath语法表改编自Goessner的路径语法比较。
语法元素 | 描述 |
---|---|
$ | 根(最外层的JSON元素),开始路径。 |
. or [] | 选择一个子元素。 |
.. | 递归地遍历JSON文档。 |
* | 通配符,返回所有元素。 |
[] | 下标运算符,用于访问数组元素。 |
[,] | 联合,选择多个元素。 |
[start:end:step] | 数组切片,其中start、end和step是索引值。你可以省略切片中的值(例如,[3:] ,[:8:2] )以使用默认值:start默认为第一个索引,end默认为最后一个索引,step默认为1 。使用[*] 或[:] 来选择所有元素。 |
?() | 过滤一个JSON对象或数组。支持比较运算符 == , != , < , <= , > , >= , =~ )&& , || )( , ) ) |
() | 脚本表达式。 |
@ | 当前元素,用于过滤器或脚本表达式。 |
JSONPath 示例
以下JSONPath示例使用此JSON文档,该文档存储了商店库存中物品的详细信息:
{
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
首先,在您的数据库中创建JSON文档:
JSON.SET bikes:inventory $ '{ "inventory": { "mountain_bikes": [ { "id": "bike:1", "model": "Phoebe", "description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\'s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.", "price": 1920, "specs": {"material": "carbon", "weight": 13.1}, "colors": ["black", "silver"] }, { "id": "bike:2", "model": "Quaoar", "description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we\'ve ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it\'s an impressive package for the price, making it very competitive.", "price": 2072, "specs": {"material": "aluminium", "weight": 7.9}, "colors": ["black", "white"] }, { "id": "bike:3", "model": "Weywot", "description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you\'re after a budget option, this is one of the best bikes you could get.", "price": 3264, "specs": {"material": "alloy", "weight": 13.8} } ], "commuter_bikes": [ { "id": "bike:4", "model": "Salacia", "description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\'s, this is a bike which doesn\'t break the bank and delivers craved performance. It\'s for the rider who wants both efficiency and capability.", "price": 1475, "specs": {"material": "aluminium", "weight": 16.6}, "colors": ["black", "silver"] }, { "id": "bike:5", "model": "Mimas", "description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.", "price": 3941, "specs": {"material": "alloy", "weight": 11.6} } ] }}'
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
访问示例
以下示例使用JSON.GET
命令从JSON文档中的各种路径检索数据。
您可以使用通配符操作符 *
来返回库存中所有项目的列表:
JSON.GET bikes:inventory $.inventory.*
"[[{\"id\":\"bike:1\",\"model\":\"Phoebe\",\"description\":\"This is a mid-travel trail slayer...
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
对于某些查询,多条路径可以产生相同的结果。例如,以下路径返回所有山地自行车的名称:
> JSON.GET bikes:inventory $.inventory.mountain_bikes[*].model
"[\"Phoebe\",\"Quaoar\",\"Weywot\"]"
> JSON.GET bikes:inventory '$.inventory["mountain_bikes"][*].model'
"[\"Phoebe\",\"Quaoar\",\"Weywot\"]"
> JSON.GET bikes:inventory '$..mountain_bikes[*].model'
"[\"Phoebe\",\"Quaoar\",\"Weywot\"]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
递归下降操作符 ..
可以从 JSON 文档的多个部分检索字段。以下示例返回所有库存物品的名称:
> JSON.GET bikes:inventory $..model
"[\"Phoebe\",\"Quaoar\",\"Weywot\",\"Salacia\",\"Mimas\"]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
你可以使用数组切片从数组中选择一系列元素。这个例子返回前2辆山地自行车的名称:
> JSON.GET bikes:inventory $..mountain_bikes[0:2].model
"[\"Phoebe\",\"Quaoar\"]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
过滤表达式 ?()
允许您根据特定条件选择 JSON 元素。您可以在这些表达式中使用比较运算符(==
, !=
, <
, <=
, >
, >=
,以及从版本 v2.4.2 开始,还包括 =~
)、逻辑运算符(&&
, ||
)和括号((
, )
)。过滤表达式可以应用于数组或对象,遍历数组中的所有元素或对象中的所有值,仅检索符合过滤条件的元素。
过滤器条件中的路径使用点符号,其中@
表示当前数组元素或当前对象值,$
表示顶级元素。例如,使用@.key_name
来引用嵌套值,使用$.top_level_key_name
来引用顶级值。
从版本v2.4.2开始,您可以使用比较运算符=~
将左侧的字符串值的路径与右侧的正则表达式模式进行匹配。有关更多信息,请参阅支持的正则表达式语法文档。
非字符串值不匹配。只有当左侧是字符串值的路径,右侧是硬编码字符串或字符串值的路径时,才会发生匹配。请参见下面的示例。
正则表达式匹配是部分的,这意味着像 "foo"
这样的正则表达式模式会匹配像 "barefoots"
这样的字符串。
要使匹配精确,请使用正则表达式模式 "^foo$"
。
其他JSONPath引擎可能在斜杠之间使用正则表达式模式(例如,/foo/
),
并且它们的匹配是精确的。它们可以使用正则表达式模式(如/.*foo.*/
)执行部分匹配。
筛选示例
在以下示例中,过滤器仅返回价格低于3000且重量小于10的山地自行车:
> JSON.GET bikes:inventory '$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]'
"[{\"id\":\"bike:2\",\"model\":\"Quaoar\",\"description\":\"Redesigned for the 2020 model year...
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
此示例筛选出由合金制成的自行车型号的库存:
> JSON.GET bikes:inventory '$..[?(@.specs.material == "alloy")].model'
"[\"Weywot\",\"Mimas\"]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
此示例从版本v2.4.2开始有效,仅过滤材料以"al-"开头的自行车,使用正则表达式匹配。请注意,由于正则表达式模式"(?i)al"
中的前缀(?i)
,此匹配不区分大小写:
JSON.GET bikes:inventory '$..[?(@.specs.material =~ "(?i)al")].model'
"[\"Quaoar\",\"Weywot\",\"Salacia\",\"Mimas\"]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
你也可以使用JSON对象本身的属性来指定一个正则表达式模式。
例如,我们可以为每辆山地自行车添加一个名为regex_pat
的字符串属性,
其值为"(?i)al"
以匹配材料,如前面的例子所示。我们
然后可以将regex_pat
与自行车的材料进行匹配:
> JSON.SET bikes:inventory $.inventory.mountain_bikes[0].regex_pat '"(?i)al"'
OK
> JSON.SET bikes:inventory $.inventory.mountain_bikes[1].regex_pat '"(?i)al"'
OK
> JSON.SET bikes:inventory $.inventory.mountain_bikes[2].regex_pat '"(?i)al"'
OK
> JSON.GET bikes:inventory '$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
"[\"Quaoar\",\"Weywot\"]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
更新示例
当您想要更新JSON文档的特定部分时,也可以使用JSONPath查询。
例如,你可以传递一个JSONPath到JSON.SET
命令来更新特定字段。这个例子改变了耳机列表中第一个商品的价格:
> JSON.GET bikes:inventory $..price
"[1920,2072,3264,1475,3941]"
> JSON.NUMINCRBY bikes:inventory $..price -100
"[1820,1972,3164,1375,3841]"
> JSON.NUMINCRBY bikes:inventory $..price 100
"[1920,2072,3264,1475,3941]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
您可以使用过滤表达式来仅更新符合特定条件的JSON元素。以下示例将任何价格已经低于2000的自行车的价格设置为1500:
> JSON.SET bikes:inventory '$.inventory.*[?(@.price<2000)].price' 1500
OK
> JSON.GET bikes:inventory $..price
"[1500,2072,3264,1500,3941]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
JSONPath 查询也适用于其他接受路径作为参数的 JSON 命令。例如,您可以使用 JSON.ARRAPPEND
为一副耳机添加新的颜色选项:
> JSON.ARRAPPEND bikes:inventory '$.inventory.*[?(@.price<2000)].colors' '"pink"'
1) (integer) 3
2) (integer) 3
127.0.0.1:6379> JSON.GET bikes:inventory $..[*].colors
"[[\"black\",\"silver\",\"pink\"],[\"black\",\"white\"],[\"black\",\"silver\",\"pink\"]]"
"""
Code samples for JSON doc pages:
https://redis.io/docs/latest/develop/data-types/json/
"""
import redis
r = redis.Redis(decode_responses=True)
res1 = r.json().set("bike", "$", '"Hyperion"')
print(res1) # >>> True
res2 = r.json().get("bike", "$")
print(res2) # >>> ['"Hyperion"']
res3 = r.json().type("bike", "$")
print(res3) # >>> ['string']
res4 = r.json().strlen("bike", "$")
print(res4) # >>> [10]
res5 = r.json().strappend("bike", '" (Enduro bikes)"')
print(res5) # >>> 27
res6 = r.json().get("bike", "$")
print(res6) # >>> ['"Hyperion"" (Enduro bikes)"']
res7 = r.json().set("crashes", "$", 0)
print(res7) # >>> True
res8 = r.json().numincrby("crashes", "$", 1)
print(res8) # >>> [1]
res9 = r.json().numincrby("crashes", "$", 1.5)
print(res9) # >>> [2.5]
res10 = r.json().numincrby("crashes", "$", -0.75)
print(res10) # >>> [1.75]
res11 = r.json().set("newbike", "$", ["Deimos", {"crashes": 0}, None])
print(res11) # >>> True
res12 = r.json().get("newbike", "$")
print(res12) # >>> ['["Deimos", { "crashes": 0 }, null]']
res13 = r.json().get("newbike", "$[1].crashes")
print(res13) # >>> ['0']
res14 = r.json().delete("newbike", "$.[-1]")
print(res14) # >>> [1]
res15 = r.json().get("newbike", "$")
print(res15) # >>> [['Deimos', {'crashes': 0}]]
res16 = r.json().set("riders", "$", [])
print(res16) # >>> True
res17 = r.json().arrappend("riders", "$", "Norem")
print(res17) # >>> [1]
res18 = r.json().get("riders", "$")
print(res18) # >>> [['Norem']]
res19 = r.json().arrinsert("riders", "$", 1, "Prickett", "Royce", "Castilla")
print(res19) # >>> [4]
res20 = r.json().get("riders", "$")
print(res20) # >>> [['Norem', 'Prickett', 'Royce', 'Castilla']]
res21 = r.json().arrtrim("riders", "$", 1, 1)
print(res21) # >>> [1]
res22 = r.json().get("riders", "$")
print(res22) # >>> [['Prickett']]
res23 = r.json().arrpop("riders", "$")
print(res23) # >>> ['"Prickett"']
res24 = r.json().arrpop("riders", "$")
print(res24) # >>> [None]
res25 = r.json().set(
"bike:1", "$", {"model": "Deimos", "brand": "Ergonom", "price": 4972}
)
print(res25) # >>> True
res26 = r.json().objlen("bike:1", "$")
print(res26) # >>> [3]
res27 = r.json().objkeys("bike:1", "$")
print(res27) # >>> [['model', 'brand', 'price']]
inventory_json = {
"inventory": {
"mountain_bikes": [
{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic "
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
"gives plenty of gear range to tackle hills and there\u2019s room for "
"mudguards and a rack too. This is the bike for the rider who wants "
"trail manners with low fuss ownership.",
"price": 1920,
"specs": {"material": "carbon", "weight": 13.1},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike "
"impressed our testers and is the best all-around trail bike we've "
"ever tested. The Shimano gear system effectively does away with an "
"external cassette, so is super low maintenance in terms of wear "
"and tear. All in all it's an impressive package for the price, "
"making it very competitive.",
"price": 2072,
"specs": {"material": "aluminium", "weight": 7.9},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older "
"a durable and uberlight mountain bike for their first experience "
"on tracks and easy cruising through forests and fields. A set of "
"powerful Shimano hydraulic disc brakes provide ample stopping "
"ability. If you're after a budget option, this is one of the best "
"bikes you could get.",
"price": 3264,
"specs": {"material": "alloy", "weight": 13.8},
},
],
"commuter_bikes": [
{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just "
"wants a bike to get about on With a slick-shifting Claris gears "
"from Shimano\u2019s, this is a bike which doesn\u2019t break the "
"bank and delivers craved performance. It\u2019s for the rider "
"who wants both efficiency and capability.",
"price": 1475,
"specs": {"material": "aluminium", "weight": 16.6},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high "
"scores in last years Bike of the year report. The carefully "
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an "
"easy-on-the-legs bottom gear for climbing, and the high-quality "
"Vittoria Zaffiro tires give balance and grip.It includes "
"a low-step frame , our memory foam seat, bump-resistant shocks and "
"conveniently placed thumb throttle. Put it all together and you "
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {"material": "alloy", "weight": 11.6},
},
],
}
}
res1 = r.json().set("bikes:inventory", "$", inventory_json)
print(res1) # >>> True
res2 = r.json().get("bikes:inventory", "$.inventory.*")
print(res2)
# >>> [[{'id': 'bike:1', 'model': 'Phoebe',
# >>> 'description': 'This is a mid-travel trail slayer...
res3 = r.json().get("bikes:inventory", "$.inventory.mountain_bikes[*].model")
print(res3) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res4 = r.json().get("bikes:inventory", '$.inventory["mountain_bikes"][*].model')
print(res4) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res5 = r.json().get("bikes:inventory", "$..mountain_bikes[*].model")
print(res5) # >>> [['Phoebe', 'Quaoar', 'Weywot']]
res6 = r.json().get("bikes:inventory", "$..model")
print(res6) # >>> [['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']]
res7 = r.json().get("bikes:inventory", "$..mountain_bikes[0:2].model")
print(res7) # >>> [['Phoebe', 'Quaoar']]
res8 = r.json().get(
"bikes:inventory",
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
)
print(res8)
# >>> [{'id': 'bike:2', 'model': 'Quaoar',
# 'description': "Redesigned for the 2020 model year...
res9 = r.json().get("bikes:inventory", "$..[?(@.specs.material == 'alloy')].model")
print(res9) # >>> ['Weywot', 'Mimas']
res10 = r.json().get("bikes:inventory", "$..[?(@.specs.material =~ '(?i)al')].model")
print(res10) # >>> ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
res11 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[0].regex_pat", "(?i)al"
)
res12 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[1].regex_pat", "(?i)al"
)
res13 = r.json().set(
"bikes:inventory", "$.inventory.mountain_bikes[2].regex_pat", "(?i)al"
)
res14 = r.json().get(
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
)
print(res14) # >>> ['Quaoar', 'Weywot']
res15 = r.json().get("bikes:inventory", "$..price")
print(res15) # >>> [1920, 2072, 3264, 1475, 3941]
res16 = r.json().numincrby("bikes:inventory", "$..price", -100)
print(res16) # >>> [1820, 1972, 3164, 1375, 3841]
res17 = r.json().numincrby("bikes:inventory", "$..price", 100)
print(res17) # >>> [1920, 2072, 3264, 1475, 3941]
res18 = r.json().set("bikes:inventory", "$.inventory.*[?(@.price<2000)].price", 1500)
res19 = r.json().get("bikes:inventory", "$..price")
print(res19) # >>> [1500, 2072, 3264, 1500, 3941]
res20 = r.json().arrappend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
)
print(res20) # >>> [3, 3]
res21 = r.json().get("bikes:inventory", "$..[*].colors")
print(
res21
) # >>> [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import assert from 'assert';
import {
createClient
} from 'redis';
const client = await createClient();
await client.connect();
const res1 = await client.json.set("bike", "$", '"Hyperion"');
console.log(res1); // OK
const res2 = await client.json.get("bike", "$");
console.log(res2); // "Hyperion"
const res3 = await client.json.type("bike", "$");
console.log(res3); // [ 'string' ]
const res4 = await client.json.strLen("bike", "$");
console.log(res4) // [10]
const res5 = await client.json.strAppend("bike", '" (Enduro bikes)"');
console.log(res5) // 27
const res6 = await client.json.get("bike", "$");
console.log(res6) // ['"Hyperion"" (Enduro bikes)"']
const res7 = await client.json.set("crashes", "$", 0);
console.log(res7) // OK
const res8 = await client.json.numIncrBy("crashes", "$", 1);
console.log(res8) // [1]
const res9 = await client.json.numIncrBy("crashes", "$", 1.5);
console.log(res9) // [2.5]
const res10 = await client.json.numIncrBy("crashes", "$", -0.75);
console.log(res10) // [1.75]
const res11 = await client.json.set("newbike", "$", ["Deimos", {"crashes": 0 }, null]);
console.log(res11); // OK
const res12 = await client.json.get("newbike", "$");
console.log(res12); // [ 'Deimos', { crashes: 0 }, null ]
const res13 = await client.json.get("newbike", "$[1].crashes");
console.log(res13); // [ 'Deimos', { crashes: 0 }, null ]
const res14 = await client.json.del("newbike", "$.[-1]");
console.log(res14); // [1]
const res15 = await client.json.get("newbike", "$");
console.log(res15); // [ 'Deimos', { crashes: 0 } ]
const res16 = await client.json.set("riders", "$", []);
console.log(res16); // OK
const res17 = await client.json.arrAppend("riders", "$", "Norem");
console.log(res17); // [1]
const res18 = await client.json.get("riders", "$");
console.log(res18); // [ 'Norem' ]
const res19 = await client.json.arrInsert("riders", "$", 1, "Prickett", "Royse", "Castilla");
console.log(res19); // [4]
const res20 = await client.json.get("riders", "$");
console.log(res20); // [ 'Norem', 'Prickett', 'Royse', 'Castilla' ]
const res21 = await client.json.arrTrim("riders", "$", 1, 1);
console.log(res21); // [1]
const res22 = await client.json.get("riders", "$");
console.log(res22); // [ 'Prickett' ]
const res23 = await client.json.arrPop("riders", "$");
console.log(res23); // [ 'Prickett' ]
const res24 = await client.json.arrPop("riders", "$");
console.log(res24); // [null]
const res25 = await client.json.set(
"bike:1", "$", {
"model": "Deimos",
"brand": "Ergonom",
"price": 4972
}
);
console.log(res25); // OK
const res26 = await client.json.objLen("bike:1", "$");
console.log(res26); // [3]
const res27 = await client.json.objKeys("bike:1", "$");
console.log(res27); // [['model', 'brand', 'price']]
const inventoryJSON = {
"inventory": {
"mountain_bikes": [{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.",
"price": 1920,
"specs": {
"material": "carbon",
"weight": 13.1
},
"colors": ["black", "silver"],
},
{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
"price": 2072,
"specs": {
"material": "aluminium",
"weight": 7.9
},
"colors": ["black", "white"],
},
{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
"price": 3264,
"specs": {
"material": "alloy",
"weight": 13.8
},
},
],
"commuter_bikes": [{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability.",
"price": 1475,
"specs": {
"material": "aluminium",
"weight": 16.6
},
"colors": ["black", "silver"],
},
{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": {
"material": "alloy",
"weight": 11.6
},
},
],
}
};
const res28 = await client.json.set("bikes:inventory", "$", inventoryJSON);
console.log(res28); // OK
const res29 = await client.json.get("bikes:inventory", {
path: "$.inventory.*"
});
console.log(res29);
/*
[
[
{
id: 'bike:1',
model: 'Phoebe',
description: 'This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there’s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership.',
price: 1920,
specs: [Object],
colors: [Array]
},
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: [Object],
colors: [Array]
},
{
id: 'bike:3',
model: 'Weywot',
description: "This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get.",
price: 3264,
specs: [Object]
}
],
[
{
id: 'bike:4',
model: 'Salacia',
description: 'This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance. It’s for the rider who wants both efficiency and capability.',
price: 1475,
specs: [Object],
colors: [Array]
},
{
id: 'bike:5',
model: 'Mimas',
description: 'A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price.',
price: 3941,
specs: [Object]
}
]
]
*/
const res30 = await client.json.get("bikes:inventory", {
path: "$.inventory.mountain_bikes[*].model"
});
console.log(res30); // ['Phoebe', 'Quaoar', 'Weywot']
const res31 = await client.json.get("bikes:inventory", {
path: '$.inventory["mountain_bikes"][*].model'
});
console.log(res31); // ['Phoebe', 'Quaoar', 'Weywot']
const res32 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[*].model"
});
console.log(res32); // ['Phoebe', 'Quaoar', 'Weywot']
const res33 = await client.json.get("bikes:inventory", {
path: "$..model"
});
console.log(res33); // ['Phoebe', 'Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res34 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[0:2].model"
});
console.log(res34); // ['Phoebe', 'Quaoar']
const res35 = await client.json.get("bikes:inventory", {
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
});
console.log(res35);
/*
[
{
id: 'bike:2',
model: 'Quaoar',
description: "Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and teaawait client. All in all it's an impressive package for the price, making it very competitive.",
price: 2072,
specs: { material: 'aluminium', weight: 7.9 },
colors: [ 'black', 'white' ]
}
]
*/
// names of bikes made from an alloy
const res36 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material == 'alloy')].model"
});
console.log(res36); // ['Weywot', 'Mimas']
const res37 = await client.json.get("bikes:inventory", {
path: "$..[?(@.specs.material =~ '(?i)al')].model"
});
console.log(res37); // ['Quaoar', 'Weywot', 'Salacia', 'Mimas']
const res37a = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[0].regex_pat',
'(?i)al'
);
const res37b = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[1].regex_pat',
'(?i)al'
);
const res37c = await client.json.set(
'bikes:inventory',
'$.inventory.mountain_bikes[2].regex_pat',
'(?i)al'
);
const res37d = await client.json.get(
'bikes:inventory',
'$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model'
);
console.log(res37d); // ['Quaoar', 'Weywot']
const res38 = await client.json.get("bikes:inventory", {
path: "$..price"
});
console.log(res38); // [1920, 2072, 3264, 1475, 3941]
const res39 = await client.json.numIncrBy("bikes:inventory", "$..price", -100);
console.log(res39); // [1820, 1972, 3164, 1375, 3841]
const res40 = await client.json.numIncrBy("bikes:inventory", "$..price", 100);
console.log(res40); // [1920, 2072, 3264, 1475, 3941]
const res40a = await client.json.set(
'bikes:inventory',
'$.inventory.*[?(@.price<2000)].price',
1500
);
// Get all prices from the inventory
const res40b = await client.json.get(
'bikes:inventory',
'$..price'
);
console.log(res40b); // [1500, 2072, 3264, 1500, 3941]
const res41 = await client.json.arrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
console.log(res41); // [3, 3]
const res42 = await client.json.get("bikes:inventory", {
path: "$..[*].colors"
});
console.log(res42); // [['black', 'silver', 'pink'], ['black', 'white'], ['black', 'silver', 'pink']]
import redis.clients.jedis.UnifiedJedis;
import redis.clients.jedis.json.Path2;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonExample {
public void run() {
UnifiedJedis jedis = new UnifiedJedis("redis://localhost:6379");
String res1 = jedis.jsonSet("bike", new Path2("$"), "\"Hyperion\"");
System.out.println(res1); // >>> OK
Object res2 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res2); // >>> ["Hyperion"]
List<Class<?>> res3 = jedis.jsonType("bike", new Path2("$"));
System.out.println(res3); // >>> [class java.lang.String]
// Tests for 'set_get' step.
List<Long> res4 = jedis.jsonStrLen("bike", new Path2("$"));
System.out.println(res4); // >>> [8]
List<Long> res5 = jedis.jsonStrAppend("bike", new Path2("$"), " (Enduro bikes)");
System.out.println(res5); // >>> [23]
Object res6 = jedis.jsonGet("bike", new Path2("$"));
System.out.println(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
String res7 = jedis.jsonSet("crashes", new Path2("$"), 0);
System.out.println(res7); // >>> OK
Object res8 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1);
System.out.println(res8); // >>> [1]
Object res9 = jedis.jsonNumIncrBy("crashes", new Path2("$"), 1.5);
System.out.println(res9); // >>> [2.5]
Object res10 = jedis.jsonNumIncrBy("crashes", new Path2("$"), -0.75);
System.out.println(res10); // >>> [1.75]
// Tests for 'num' step.
String res11 = jedis.jsonSet("newbike", new Path2("$"),
new JSONArray()
.put("Deimos")
.put(new JSONObject().put("crashes", 0))
.put((Object) null)
);
System.out.println(res11); // >>> OK
Object res12 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res12); // >>> [["Deimos",{"crashes":0},null]]
Object res13 = jedis.jsonGet("newbike", new Path2("$[1].crashes"));
System.out.println(res13); // >>> [0]
long res14 = jedis.jsonDel("newbike", new Path2("$.[-1]"));
System.out.println(res14); // >>> 1
Object res15 = jedis.jsonGet("newbike", new Path2("$"));
System.out.println(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
String res16 = jedis.jsonSet("riders", new Path2("$"), new JSONArray());
System.out.println(res16); // >>> OK
List<Long> res17 = jedis.jsonArrAppendWithEscape("riders", new Path2("$"), "Norem");
System.out.println(res17); // >>> [1]
Object res18 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res18); // >>> [["Norem"]]
List<Long> res19 = jedis.jsonArrInsertWithEscape(
"riders", new Path2("$"), 1, "Prickett", "Royce", "Castilla"
);
System.out.println(res19); // >>> [4]
Object res20 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res20);
// >>> [["Norem","Prickett","Royce","Castilla"]]
List<Long> res21 = jedis.jsonArrTrim("riders", new Path2("$"), 1, 1);
System.out.println(res21); // >>> [1]
Object res22 = jedis.jsonGet("riders", new Path2("$"));
System.out.println(res22); // >>> [["Prickett"]]
Object res23 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res23); // >>> [Prickett]
Object res24 = jedis.jsonArrPop("riders", new Path2("$"));
System.out.println(res24); // >>> [null]
// Tests for 'arr2' step.
String res25 = jedis.jsonSet("bike:1", new Path2("$"),
new JSONObject()
.put("model", "Deimos")
.put("brand", "Ergonom")
.put("price", 4972)
);
System.out.println(res25); // >>> OK
List<Long> res26 = jedis.jsonObjLen("bike:1", new Path2("$"));
System.out.println(res26); // >>> [3]
List<List<String>> res27 = jedis.jsonObjKeys("bike:1", new Path2("$"));
System.out.println(res27); // >>> [[price, model, brand]]
// Tests for 'obj' step.
String inventory_json = "{"
+ " \"inventory\": {"
+ " \"mountain_bikes\": ["
+ " {"
+ " \"id\": \"bike:1\","
+ " \"model\": \"Phoebe\","
+ " \"description\": \"This is a mid-travel trail slayer that is a "
+ "fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset "
+ "gives plenty of gear range to tackle hills and there\u2019s room for mudguards "
+ "and a rack too. This is the bike for the rider who wants trail manners with "
+ "low fuss ownership.\","
+ " \"price\": 1920,"
+ " \"specs\": {\"material\": \"carbon\", \"weight\": 13.1},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:2\","
+ " \"model\": \"Quaoar\","
+ " \"description\": \"Redesigned for the 2020 model year, this "
+ "bike impressed our testers and is the best all-around trail bike we've ever "
+ "tested. The Shimano gear system effectively does away with an external cassette, "
+ "so is super low maintenance in terms of wear and tear. All in all it's an "
+ "impressive package for the price, making it very competitive.\","
+ " \"price\": 2072,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 7.9},"
+ " \"colors\": [\"black\", \"white\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:3\","
+ " \"model\": \"Weywot\","
+ " \"description\": \"This bike gives kids aged six years and older "
+ "a durable and uberlight mountain bike for their first experience on tracks and easy "
+ "cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes "
+ "provide ample stopping ability. If you're after a budget option, this is one of the "
+ "best bikes you could get.\","
+ " \"price\": 3264,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 13.8}"
+ " }"
+ " ],"
+ " \"commuter_bikes\": ["
+ " {"
+ " \"id\": \"bike:4\","
+ " \"model\": \"Salacia\","
+ " \"description\": \"This bike is a great option for anyone who just "
+ "wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, "
+ "this is a bike which doesn\u2019t break the bank and delivers craved performance. "
+ "It\u2019s for the rider who wants both efficiency and capability.\","
+ " \"price\": 1475,"
+ " \"specs\": {\"material\": \"aluminium\", \"weight\": 16.6},"
+ " \"colors\": [\"black\", \"silver\"]"
+ " },"
+ " {"
+ " \"id\": \"bike:5\","
+ " \"model\": \"Mimas\","
+ " \"description\": \"A real joy to ride, this bike got very high scores "
+ "in last years Bike of the year report. The carefully crafted 50-34 tooth chainset "
+ "and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the "
+ "high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step "
+ "frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb "
+ "throttle. Put it all together and you get a bike that helps redefine what can be "
+ "done for this price.\","
+ " \"price\": 3941,"
+ " \"specs\": {\"material\": \"alloy\", \"weight\": 11.6}"
+ " }"
+ " ]"
+ " }"
+ "}";
String res28 = jedis.jsonSet("bikes:inventory", new Path2("$"), inventory_json);
System.out.println(res28); // >>> OK
// Tests for 'set_bikes' step.
Object res29 = jedis.jsonGet("bikes:inventory", new Path2("$.inventory.*"));
System.out.println(res29);
// >>> [[{"specs":{"material":"carbon","weight":13.1},"price":1920, ...
// Tests for 'get_bikes' step.
Object res30 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[*].model")
);
System.out.println(res30); // >>> ["Phoebe","Quaoar","Weywot"]
Object res31 = jedis.jsonGet(
"bikes:inventory", new Path2("$.inventory[\"mountain_bikes\"][*].model")
);
System.out.println(res31); // >>> ["Phoebe","Quaoar","Weywot"]
Object res32 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[*].model")
);
System.out.println(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
Object res33 = jedis.jsonGet("bikes:inventory", new Path2("$..model"));
System.out.println(res33);
// >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
Object res34 = jedis.jsonGet(
"bikes:inventory", new Path2("$..mountain_bikes[0:2].model")
);
System.out.println(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
Object res35 = jedis.jsonGet(
"bikes:inventory",
new Path2("$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]")
);
System.out.println(res35);
// >>> [{"specs":{"material":"aluminium","weight":7.9},"price":2072,...
// Tests for 'filter1' step.
Object res36 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material == 'alloy')].model")
);
System.out.println(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
Object res37 = jedis.jsonGet(
"bikes:inventory", new Path2("$..[?(@.specs.material =~ '(?i)al')].model")
);
System.out.println(res37);
// >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[0].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[1].regex_pat"),
"\"(?i)al\""
);
jedis.jsonSet(
"bikes:inventory", new Path2("$.inventory.mountain_bikes[2].regex_pat"),
"\"(?i)al\""
);
Object res38 = jedis.jsonGet(
"bikes:inventory",
new Path2("$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model")
);
System.out.println(res38); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
Object res39 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res39);
// >>> [1920,2072,3264,1475,3941]
Object res40 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), -100);
System.out.println(res40); // >>> [1820,1972,3164,1375,3841]
Object res41 = jedis.jsonNumIncrBy("bikes:inventory", new Path2("$..price"), 100);
System.out.println(res41); // >>> [1920,2072,3264,1475,3941]
// Tests for 'update_bikes' step.
jedis.jsonSet("bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].price"), 1500);
Object res42 = jedis.jsonGet("bikes:inventory", new Path2("$..price"));
System.out.println(res42); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
List<Long> res43 = jedis.jsonArrAppendWithEscape(
"bikes:inventory", new Path2("$.inventory.*[?(@.price<2000)].colors"),
"\"pink\""
);
System.out.println(res43); // >>> [3, 3]
Object res44 = jedis.jsonGet("bikes:inventory", new Path2("$..[*].colors"));
System.out.println(res44);
// >>> [["black","silver","\"pink\""],["black","white"],["black","silver","\"pink\""]]
// Tests for 'update_filters2' step.
jedis.close();
}
}
package example_commands_test
import (
"context"
"fmt"
"github.com/redis/go-redis/v9"
)
func ExampleClient_setget() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res1, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
res2, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res2) // >>> ["Hyperion"]
res3, err := rdb.JSONType(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res3) // >>> [[string]]
}
func ExampleClient_str() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bike", "$",
"\"Hyperion\"",
).Result()
if err != nil {
panic(err)
}
res4, err := rdb.JSONStrLen(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res4[0]) // >>> 8
res5, err := rdb.JSONStrAppend(ctx, "bike", "$", "\" (Enduro bikes)\"").Result()
if err != nil {
panic(err)
}
fmt.Println(*res5[0]) // >>> 23
res6, err := rdb.JSONGet(ctx, "bike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Hyperion (Enduro bikes)"]
}
func ExampleClient_num() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res7, err := rdb.JSONSet(ctx, "crashes", "$", 0).Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> OK
res8, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1).Result()
if err != nil {
panic(err)
}
fmt.Println(res8) // >>> [1]
res9, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", 1.5).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> [2.5]
res10, err := rdb.JSONNumIncrBy(ctx, "crashes", "$", -0.75).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> [1.75]
}
func ExampleClient_arr() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res11, err := rdb.JSONSet(ctx, "newbike", "$",
[]interface{}{
"Deimos",
map[string]interface{}{"crashes": 0},
nil,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> [["Deimos",{"crashes":0},null]]
res13, err := rdb.JSONGet(ctx, "newbike", "$[1].crashes").Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> [0]
res14, err := rdb.JSONDel(ctx, "newbike", "$.[-1]").Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> 1
res15, err := rdb.JSONGet(ctx, "newbike", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [["Deimos",{"crashes":0}]]
}
func ExampleClient_arr2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res16, err := rdb.JSONSet(ctx, "riders", "$", []interface{}{}).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> OK
res17, err := rdb.JSONArrAppend(ctx, "riders", "$", "\"Norem\"").Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1]
res18, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> [["Norem"]]
res19, err := rdb.JSONArrInsert(ctx, "riders", "$", 1,
"\"Prickett\"", "\"Royce\"", "\"Castilla\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // [3]
res20, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [["Norem", "Prickett", "Royce", "Castilla"]]
rangeStop := 1
res21, err := rdb.JSONArrTrimWithArgs(ctx, "riders", "$",
&redis.JSONArrTrimArgs{Start: 1, Stop: &rangeStop},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res21) // >>> [1]
res22, err := rdb.JSONGet(ctx, "riders", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res22) // >>> [["Prickett"]]
res23, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res23) // >>> [["Prickett"]]
res24, err := rdb.JSONArrPop(ctx, "riders", "$", -1).Result()
if err != nil {
panic(err)
}
fmt.Println(res24) // []
}
func ExampleClient_obj() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
res25, err := rdb.JSONSet(ctx, "bike:1", "$",
map[string]interface{}{
"model": "Deimos",
"brand": "Ergonom",
"price": 4972,
},
).Result()
if err != nil {
panic(err)
}
fmt.Println(res25) // >>> OK
res26, err := rdb.JSONObjLen(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(*res26[0]) // >>> 3
res27, err := rdb.JSONObjKeys(ctx, "bike:1", "$").Result()
if err != nil {
panic(err)
}
fmt.Println(res27) // >>> [brand model price]
}
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
func ExampleClient_setbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
var inventory_json = map[string]interface{}{
"inventory": map[string]interface{}{
"mountain_bikes": []interface{}{
map[string]interface{}{
"id": "bike:1",
"model": "Phoebe",
"description": "This is a mid-travel trail slayer that is a fantastic " +
"daily driver or one bike quiver. The Shimano Claris 8-speed groupset " +
"gives plenty of gear range to tackle hills and there\u2019s room for " +
"mudguards and a rack too. This is the bike for the rider who wants " +
"trail manners with low fuss ownership.",
"price": 1920,
"specs": map[string]interface{}{"material": "carbon", "weight": 13.1},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:2",
"model": "Quaoar",
"description": "Redesigned for the 2020 model year, this bike " +
"impressed our testers and is the best all-around trail bike we've " +
"ever tested. The Shimano gear system effectively does away with an " +
"external cassette, so is super low maintenance in terms of wear " +
"and tear. All in all it's an impressive package for the price, " +
"making it very competitive.",
"price": 2072,
"specs": map[string]interface{}{"material": "aluminium", "weight": 7.9},
"colors": []interface{}{"black", "white"},
},
map[string]interface{}{
"id": "bike:3",
"model": "Weywot",
"description": "This bike gives kids aged six years and older " +
"a durable and uberlight mountain bike for their first experience " +
"on tracks and easy cruising through forests and fields. A set of " +
"powerful Shimano hydraulic disc brakes provide ample stopping " +
"ability. If you're after a budget option, this is one of the best " +
"bikes you could get.",
"price": 3264,
"specs": map[string]interface{}{"material": "alloy", "weight": 13.8},
},
},
"commuter_bikes": []interface{}{
map[string]interface{}{
"id": "bike:4",
"model": "Salacia",
"description": "This bike is a great option for anyone who just " +
"wants a bike to get about on With a slick-shifting Claris gears " +
"from Shimano\u2019s, this is a bike which doesn\u2019t break the " +
"bank and delivers craved performance. It\u2019s for the rider " +
"who wants both efficiency and capability.",
"price": 1475,
"specs": map[string]interface{}{"material": "aluminium", "weight": 16.6},
"colors": []interface{}{"black", "silver"},
},
map[string]interface{}{
"id": "bike:5",
"model": "Mimas",
"description": "A real joy to ride, this bike got very high " +
"scores in last years Bike of the year report. The carefully " +
"crafted 50-34 tooth chainset and 11-32 tooth cassette give an " +
"easy-on-the-legs bottom gear for climbing, and the high-quality " +
"Vittoria Zaffiro tires give balance and grip.It includes " +
"a low-step frame , our memory foam seat, bump-resistant shocks and " +
"conveniently placed thumb throttle. Put it all together and you " +
"get a bike that helps redefine what can be done for this price.",
"price": 3941,
"specs": map[string]interface{}{"material": "alloy", "weight": 11.6},
},
},
},
}
res1, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
fmt.Println(res1) // >>> OK
}
func ExampleClient_getbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res2, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$.inventory.*",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res2)
// >>>
// [
// [
// {
// "colors": [
// "black",
// "silver"
// ...
}
func ExampleClient_getmtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res3, err := rdb.JSONGet(ctx, "bikes:inventory",
"$.inventory.mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res3)
// >>> ["Phoebe","Quaoar","Weywot"]
res4, err := rdb.JSONGet(ctx,
"bikes:inventory", "$.inventory[\"mountain_bikes\"][*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res4)
// >>> ["Phoebe","Quaoar","Weywot"]
res5, err := rdb.JSONGet(ctx,
"bikes:inventory", "$..mountain_bikes[*].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res5)
// >>> ["Phoebe","Quaoar","Weywot"]
}
func ExampleClient_getmodels() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res6, err := rdb.JSONGet(ctx, "bikes:inventory", "$..model").Result()
if err != nil {
panic(err)
}
fmt.Println(res6) // >>> ["Salacia","Mimas","Phoebe","Quaoar","Weywot"]
}
func ExampleClient_get2mtnbikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res7, err := rdb.JSONGet(ctx, "bikes:inventory", "$..mountain_bikes[0:2].model").Result()
if err != nil {
panic(err)
}
fmt.Println(res7) // >>> ["Phoebe","Quaoar"]
}
func ExampleClient_filter1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res8, err := rdb.JSONGetWithArgs(ctx, "bikes:inventory",
&redis.JSONGetArgs{Indent: " ", Newline: "\n", Space: " "},
"$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res8)
// >>>
// [
// {
// "colors": [
// "black",
// "white"
// ],
// "description": "Redesigned for the 2020 model year
// ...
}
func ExampleClient_filter2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res9, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material == 'alloy')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res9) // >>> ["Mimas","Weywot"]
}
func ExampleClient_filter3() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res10, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$..[?(@.specs.material =~ '(?i)al')].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res10) // >>> ["Salacia","Mimas","Quaoar","Weywot"]
}
func ExampleClient_filter4() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res11, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res11) // >>> OK
res12, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res12) // >>> OK
res13, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res13) // >>> OK
res14, err := rdb.JSONGet(ctx,
"bikes:inventory",
"$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res14) // >>> ["Quaoar","Weywot"]
}
func ExampleClient_updatebikes() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res15, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res15) // >>> [1475,3941,1920,2072,3264]
res16, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", -100).Result()
if err != nil {
panic(err)
}
fmt.Println(res16) // >>> [1375,3841,1820,1972,3164]
res17, err := rdb.JSONNumIncrBy(ctx, "bikes:inventory", "$..price", 100).Result()
if err != nil {
panic(err)
}
fmt.Println(res17) // >>> [1475,3941,1920,2072,3264]
}
func ExampleClient_updatefilters1() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res18, err := rdb.JSONSet(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500,
).Result()
if err != nil {
panic(err)
}
fmt.Println(res18) // >>> OK
res19, err := rdb.JSONGet(ctx, "bikes:inventory", "$..price").Result()
if err != nil {
panic(err)
}
fmt.Println(res19) // >>> [1500,3941,1500,2072,3264]
}
func ExampleClient_updatefilters2() {
ctx := context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password docs
DB: 0, // use default DB
})
_, err := rdb.JSONSet(ctx, "bikes:inventory", "$", inventory_json).Result()
if err != nil {
panic(err)
}
res20, err := rdb.JSONArrAppend(ctx,
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].colors",
"\"pink\"",
).Result()
if err != nil {
panic(err)
}
fmt.Println(res20) // >>> [3 3]
res21, err := rdb.JSONGet(ctx, "bikes:inventory", "$..[*].colors").Result()
if err != nil {
panic(err)
}
fmt.Println(res21)
// >>> [["black","silver","pink"],["black","silver","pink"],["black","white"]]
}
using NRedisStack;
using NRedisStack.RedisStackCommands;
using NRedisStack.Tests;
using StackExchange.Redis;
public class Json_tutorial
{
public void run()
{
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
var db = muxer.GetDatabase();
bool res1 = db.JSON().Set("bike", "$", "\"Hyperion\"");
Console.WriteLine(res1); // >>> True
RedisResult res2 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res2); // >>> ["Hyperion"]
JsonType[] res3 = db.JSON().Type("bike", "$");
Console.WriteLine(string.Join(", ", res3)); // >>> STRING
// Tests for 'set_get' step.
long?[] res4 = db.JSON().StrLen("bike", "$");
Console.Write(string.Join(", ", res4)); // >>> 8
long?[] res5 = db.JSON().StrAppend("bike", " (Enduro bikes)");
Console.WriteLine(string.Join(", ", res5)); // >>> 23
RedisResult res6 = db.JSON().Get("bike", path: "$");
Console.WriteLine(res6); // >>> ["Hyperion (Enduro bikes)"]
// Tests for 'str' step.
bool res7 = db.JSON().Set("crashes", "$", 0);
Console.WriteLine(res7); // >>> True
double?[] res8 = db.JSON().NumIncrby("crashes", "$", 1);
Console.WriteLine(res8); // >>> 1
double?[] res9 = db.JSON().NumIncrby("crashes", "$", 1.5);
Console.WriteLine(res9); // >>> 2.5
double?[] res10 = db.JSON().NumIncrby("crashes", "$", -0.75);
Console.WriteLine(res9); // >>> 1.75
// Tests for 'num' step.
bool res11 = db.JSON().Set("newbike", "$", new object?[] { "Deimos", new { crashes = 0 }, null });
Console.WriteLine(res11); // >>> True
RedisResult res12 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res12); // >>> [["Deimos",{"crashes":0},null]]
RedisResult res13 = db.JSON().Get("newbike", path: "$[1].crashes");
Console.WriteLine(res13); // >>> [0]
long res14 = db.JSON().Del("newbike", "$.[-1]");
Console.WriteLine(res14); // >>> 1
RedisResult res15 = db.JSON().Get("newbike", path: "$");
Console.WriteLine(res15); // >>> [["Deimos",{"crashes":0}]]
// Tests for 'arr' step.
bool res16 = db.JSON().Set("riders", "$", new object[] { });
Console.WriteLine(res16); // >>> True
long?[] res17 = db.JSON().ArrAppend("riders", "$", "Norem");
Console.WriteLine(string.Join(", ", res17)); // >>> 1
RedisResult res18 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res18); // >>> [["Norem"]]
long?[] res19 = db.JSON().ArrInsert("riders", "$", 1, "Prickett", "Royce", "Castilla");
Console.WriteLine(string.Join(", ", res19)); // >>> 4
RedisResult res20 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res20); // >>> [["Norem","Prickett","Royce","Castilla"]]
long?[] res21 = db.JSON().ArrTrim("riders", "$", 1, 1);
Console.WriteLine(string.Join(", ", res21)); // 1
RedisResult res22 = db.JSON().Get("riders", path: "$");
Console.WriteLine(res22); // >>> [["Prickett"]]
RedisResult[] res23 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res23)); // >>> "Prickett"
RedisResult[] res24 = db.JSON().ArrPop("riders", "$");
Console.WriteLine(string.Join(", ", (object[])res24)); // >>> <Empty string>
// Tests for 'arr2' step.
bool res25 = db.JSON().Set("bike:1", "$",
new { model = "Deimos", brand = "Ergonom", price = 4972 }
);
Console.WriteLine(res25); // >>> True
long?[] res26 = db.JSON().ObjLen("bike:1", "$");
Console.WriteLine(string.Join(", ", res26)); // >>> 3
IEnumerable<HashSet<string>> res27 = db.JSON().ObjKeys("bike:1", "$");
Console.WriteLine(
string.Join(", ", res27.Select(b => $"{string.Join(", ", b.Select(c => $"{c}"))}"))
); // >>> model, brand, price
// Tests for 'obj' step.
string inventoryJson = @"
{
""inventory"": {
""mountain_bikes"": [
{
""id"": ""bike:1"",
""model"": ""Phoebe"",
""description"": ""This is a mid-travel trail slayer that is a fantastic daily driver or one bike quiver. The Shimano Claris 8-speed groupset gives plenty of gear range to tackle hills and there\u2019s room for mudguards and a rack too. This is the bike for the rider who wants trail manners with low fuss ownership."",
""price"": 1920,
""specs"": {""material"": ""carbon"", ""weight"": 13.1},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:2"",
""model"": ""Quaoar"",
""description"": ""Redesigned for the 2020 model year, this bike impressed our testers and is the best all-around trail bike we've ever tested. The Shimano gear system effectively does away with an external cassette, so is super low maintenance in terms of wear and tear. All in all it's an impressive package for the price, making it very competitive."",
""price"": 2072,
""specs"": {""material"": ""aluminium"", ""weight"": 7.9},
""colors"": [""black"", ""white""]
},
{
""id"": ""bike:3"",
""model"": ""Weywot"",
""description"": ""This bike gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. A set of powerful Shimano hydraulic disc brakes provide ample stopping ability. If you're after a budget option, this is one of the best bikes you could get."",
""price"": 3264,
""specs"": {""material"": ""alloy"", ""weight"": 13.8}
}
],
""commuter_bikes"": [
{
""id"": ""bike:4"",
""model"": ""Salacia"",
""description"": ""This bike is a great option for anyone who just wants a bike to get about on With a slick-shifting Claris gears from Shimano\u2019s, this is a bike which doesn\u2019t break the bank and delivers craved performance. It\u2019s for the rider who wants both efficiency and capability."",
""price"": 1475,
""specs"": {""material"": ""aluminium"", ""weight"": 16.6},
""colors"": [""black"", ""silver""]
},
{
""id"": ""bike:5"",
""model"": ""Mimas"",
""description"": ""A real joy to ride, this bike got very high scores in last years Bike of the year report. The carefully crafted 50-34 tooth chainset and 11-32 tooth cassette give an easy-on-the-legs bottom gear for climbing, and the high-quality Vittoria Zaffiro tires give balance and grip.It includes a low-step frame , our memory foam seat, bump-resistant shocks and conveniently placed thumb throttle. Put it all together and you get a bike that helps redefine what can be done for this price."",
""price"": 3941,
""specs"": {""material"": ""alloy"", ""weight"": 11.6}
}
]
}
}";
bool res28 = db.JSON().Set("bikes:inventory", "$", inventoryJson);
Console.WriteLine(res28); // >>> True
// Tests for 'set_bikes' step.
RedisResult res29 = db.JSON().Get("bikes:inventory", path: "$.inventory.*");
Console.WriteLine(res29); // >>> {[[{"id":"bike:1","model":"Phoebe", ...
// Tests for 'get_bikes' step.
RedisResult res30 = db.JSON().Get("bikes:inventory", path: "$.inventory.mountain_bikes[*].model");
Console.WriteLine(res30); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res31 = db.JSON().Get("bikes:inventory", path: "$.inventory[\"mountain_bikes\"][*].model");
Console.WriteLine(res31); // >>> ["Phoebe","Quaoar","Weywot"]
RedisResult res32 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[*].model");
Console.WriteLine(res32); // >>> ["Phoebe","Quaoar","Weywot"]
// Tests for 'get_mtnbikes' step.
RedisResult res33 = db.JSON().Get("bikes:inventory", path: "$..model");
Console.WriteLine(res33); // >>> ["Phoebe","Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'get_models' step.
RedisResult res34 = db.JSON().Get("bikes:inventory", path: "$..mountain_bikes[0:2].model");
Console.WriteLine(res34); // >>> ["Phoebe","Quaoar"]
// Tests for 'get2mtnbikes' step.
RedisResult res35 = db.JSON().Get(
"bikes:inventory",
path: "$..mountain_bikes[?(@.price < 3000 && @.specs.weight < 10)]"
);
Console.WriteLine(res35);
// >>> [{"id":"bike:2","model":"Quaoar","description":"Redesigned for the 2020 model year...
// Tests for 'filter1' step.
RedisResult res36 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material == 'alloy')].model"
);
Console.WriteLine(res36); // >>> ["Weywot","Mimas"]
// Tests for 'filter2' step.
RedisResult res37 = db.JSON().Get(
"bikes:inventory",
path: "$..[?(@.specs.material =~ '(?i)al')].model"
);
Console.WriteLine(res37); // >>> ["Quaoar","Weywot","Salacia","Mimas"]
// Tests for 'filter3' step.
bool res38 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[0].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res38); // >>> True
bool res39 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[1].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res39); // >>> True
bool res40 = db.JSON().Set(
"bikes:inventory",
"$.inventory.mountain_bikes[2].regex_pat",
"\"(?i)al\""
);
Console.WriteLine(res40); // >>> True
RedisResult res41 = db.JSON().Get(
"bikes:inventory",
path: "$.inventory.mountain_bikes[?(@.specs.material =~ @.regex_pat)].model"
);
Console.WriteLine(res41); // >>> ["Quaoar","Weywot"]
// Tests for 'filter4' step.
RedisResult res42 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res42); // >>> [1920,2072,3264,1475,3941]
double?[] res43 = db.JSON().NumIncrby("bikes:inventory", "$..price", -100);
Console.WriteLine(string.Join(", ", res43)); // >>> 1820, 1972, 3164, 1375, 3841
double?[] res44 = db.JSON().NumIncrby("bikes:inventory", "$..price", 100);
Console.WriteLine(string.Join(", ", res44)); // >>> 1920, 2072, 3264, 1475, 3941
// Tests for 'update_bikes' step.
bool res45 = db.JSON().Set(
"bikes:inventory",
"$.inventory.*[?(@.price<2000)].price",
1500
);
Console.WriteLine(res45); // >>> True
RedisResult res46 = db.JSON().Get("bikes:inventory", path: "$..price");
Console.WriteLine(res46); // >>> [1500,2072,3264,1500,3941]
// Tests for 'update_filters1' step.
long?[] res47 = db.JSON().ArrAppend(
"bikes:inventory", "$.inventory.*[?(@.price<2000)].colors", "pink"
);
Console.WriteLine(string.Join(", ", res47)); // >>> 3, 3
RedisResult res48 = db.JSON().Get("bikes:inventory", path: "$..[*].colors");
Console.WriteLine(res48); // >>> [["black","silver","pink"],["black","white"],["black","silver","pink"]]
// Tests for 'update_filters2' step.
}
}
旧版路径语法
RedisJSON v1 有以下路径实现。JSON v2 除了支持 JSONPath 外,仍然支持这种旧路径。
路径总是从Redis JSON值的根开始。根由一个句点字符(.
)表示。对于引用根的子元素的路径,可以选择在路径前加上根。
Redis JSON 支持使用点符号和括号符号来访问对象键。以下路径指向的是根目录下 inventory 的子项 headphones:
.inventory.headphones
inventory["headphones"]
['inventory']["headphones"]
要访问数组元素,请将其索引括在一对方括号内。索引从0开始,0表示数组的第一个元素,1表示下一个元素,依此类推。您可以使用负偏移量从数组末尾开始访问元素。例如,-1表示数组中的最后一个元素,-2表示倒数第二个元素,依此类推。
JSON 键名和路径兼容性
根据定义,JSON键可以是任何有效的JSON字符串。而路径传统上基于JavaScript(和Java)的变量命名约定。
尽管JSON可以存储包含任意键名的对象,但如果这些键名符合以下命名语法规则,您只能使用传统路径来访问这些键:
- 名称必须以字母、美元符号(
$
)或下划线(_
)字符开头 - 名称可以包含字母、数字、美元符号和下划线
- 名称区分大小写
路径评估的时间复杂度
在路径中搜索(导航到)元素的时间复杂度是从以下计算的:
- 子级别 - 路径上的每个级别都会增加一次额外的搜索
- 键搜索 - O(N)†,其中 N 是父对象中的键的数量
- 数组搜索 - O(1)
这意味着搜索路径的总体时间复杂度为O(N*M),其中N是深度,M是父对象键的数量。
† 虽然这对于N较小的对象是可以接受的,但对于较大的对象,访问可以进行优化。