Skip to content

Commit

Permalink
add changelog and few changes
Browse files Browse the repository at this point in the history
  • Loading branch information
shohamazon committed Mar 11, 2024
1 parent c368a19 commit e3633d9
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 58 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* Node: Added HVAL command ([#1022](https://github.com/aws/glide-for-redis/pull/1022))
* Node: Added PERSIST command ([#1023](https://github.com/aws/glide-for-redis/pull/1023))
* Node: Added Xadd, Xtrim commands. ([#1057](https://github.com/aws/glide-for-redis/pull/1057))
* Python: Added json module and JSON.SET JSON.GET commands ([#1056](https://github.com/aws/glide-for-redis/pull/1056))

#### Features

Expand Down
65 changes: 43 additions & 22 deletions python/python/glide/async_commands/redis_modules/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
>>> from glide import json as redisJson
>>> import json
>>> value = {'a': 1.0, 'b': 2}
>>> json_str = json.dumps(value)
>>> json_str = json.dumps(value) # Convert Python dictionary to JSON string using json.dumps()
>>> await redisJson.set(client, "doc", "$", json_str)
'OK' # Indicates successful setting of the value at path '$' in the key stored at 'doc'.
>>> await redisJson.get(client, "doc", "$")
"[{\"a\":1.0,\"b\":2}]" # Returns the value at path '$' in the JSON document stored at 'doc'.
>>> json_get = await redisJson.get(client, "doc", "$")
'OK' # Indicates successful setting of the value at path '$' in the key stored at `doc`.
>>> json_get = await redisJson.get(client, "doc", "$") # Returns the value at path '$' in the JSON document stored at `doc` as JSON string.
>>> print(json_get)
"[{\"a\":1.0,\"b\":2}]"
>>> json.loads(json_get)
[{"a": 1.0, "b" :2}]
[{"a": 1.0, "b" :2}] # JSON object retrieved from the key `doc` using json.loads()
"""
from typing import List, Optional, Union, cast

Expand All @@ -23,6 +23,37 @@
from glide.redis_client import TRedisClient


class JsonGetOptions:
"""
Represents options for formatting JSON data, to be used in the [JSON.GET](https://redis.io/commands/json.get/) command.
Args:
indent (Optional[str]): Sets an indentation string for nested levels. Defaults to None.
newline (Optional[str]): Sets a string that's printed at the end of each line. Defaults to None.
space (Optional[str]): Sets a string that's put between a key and a value. Defaults to None.
"""

def __init__(
self,
indent: Optional[str] = None,
newline: Optional[str] = None,
space: Optional[str] = None,
):
self.indent = indent
self.new_line = newline
self.space = space

def get_options(self) -> List[str]:
args = []
if self.indent:
args.extend(["INDENT", self.indent])
if self.new_line:
args.extend(["NEWLINE", self.new_line])
if self.space:
args.extend(["SPACE", self.space])
return args


async def set(
client: TRedisClient,
key: str,
Expand Down Expand Up @@ -67,9 +98,7 @@ async def get(
client: TRedisClient,
key: str,
paths: Optional[Union[str, List[str]]] = None,
indent: Optional[str] = None,
newline: Optional[str] = None,
space: Optional[str] = None,
options: Optional[JsonGetOptions] = None,
) -> Optional[str]:
"""
Retrieves the JSON value at the specified `paths` stored at `key`.
Expand All @@ -79,10 +108,8 @@ async def get(
Args:
client (TRedisClient): The Redis client to execute the command.
key (str): The key of the JSON document.
paths (Optional[Union[str, List[str]]]): The path or list of paths within the JSON document.
indent (Optional[str]): Sets an indentation string for nested levels. Defaults to None.
newline (Optional[str]): Sets a string that's printed at the end of each line. Defaults to None.
space (Optional[str]): Sets a string that's put between a key and a value. Defaults to None.
paths (Optional[Union[str, List[str]]]): The path or list of paths within the JSON document. Default is root `$`.
options (Optional[JsonGetOptions]): Options for formatting the string representation of the JSON data. See `JsonGetOptions`.
Returns:
str: A bulk string representation of the returned value.
Expand All @@ -96,20 +123,14 @@ async def get(
[{"a": 1.0, "b" :2}] # JSON object retrieved from the key `doc` using json.loads()
>>> await redisJson.get(client, "doc", "$")
"[{\"a\":1.0,\"b\":2}]" # Returns the value at path '$' in the JSON document stored at `doc`.
>>> await redisJson.get(client, "doc", ["$.a", "$.b"], indent=" ", newline="\n", space=" ")
>>> await redisJson.get(client, "doc", ["$.a", "$.b"], json.JsonGetOptions(indent=" ", newline="\n", space=" "))
"{\n \"$.a\": [\n 1.0\n ],\n \"$.b\": [\n 2\n ]\n}" # Returns the values at paths '$.a' and '$.b' in the JSON document stored at `doc`, with specified formatting options.
>>> await redisJson.get(client, "doc", "$.non_existing_path")
"[]" # Returns an empty array since the path '$.non_existing_path' does not exist in the JSON document stored at `doc`.
"""
args = [key]

if indent:
args.extend(["INDENT", indent])
if newline:
args.extend(["NEWLINE", newline])
if space:
args.extend(["SPACE", space])

if options:
args.extend(options.get_options())
if paths:
if isinstance(paths, str):
paths = [paths]
Expand Down
27 changes: 13 additions & 14 deletions python/python/tests/tests_redis_modules/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
import json as OuterJson

import pytest
from glide import json
from glide.async_commands.core import ConditionalChange, InfoSection
from glide.async_commands.redis_modules import json
from glide.async_commands.redis_modules.json import JsonGetOptions
from glide.config import ProtocolVersion
from glide.constants import OK
from glide.redis_client import TRedisClient
Expand All @@ -15,7 +16,7 @@
class TestJson:
@pytest.mark.parametrize("cluster_mode", [True, False])
@pytest.mark.parametrize("protocol", [ProtocolVersion.RESP2, ProtocolVersion.RESP3])
async def test_json_module_loadded(self, redis_client: TRedisClient):
async def test_json_module_is_loaded(self, redis_client: TRedisClient):
res = parse_info_response(await redis_client.info([InfoSection.MODULES]))
assert "ReJSON" in res["module"]

Expand All @@ -24,20 +25,18 @@ async def test_json_module_loadded(self, redis_client: TRedisClient):
async def test_json_set_get(self, redis_client: TRedisClient):
key = get_random_string(5)

assert (
await json.set(redis_client, key, "$", OuterJson.dumps({"a": 1.0, "b": 2}))
== OK
)
json_value = {"a": 1.0, "b": 2}
assert await json.set(redis_client, key, "$", OuterJson.dumps(json_value)) == OK

result = await json.get(redis_client, key, "$")
result = await json.get(redis_client, key, ".")
assert isinstance(result, str)
assert OuterJson.loads(result) == [{"a": 1.0, "b": 2}]
assert OuterJson.loads(result) == json_value

result = await json.get(redis_client, key, ["$.a", "$.b"])
assert isinstance(result, str)
assert OuterJson.loads(result) == {"$.a": [1.0], "$.b": [2]}

assert await json.get(redis_client, "non_existing_key", "$", "bar") is None
assert await json.get(redis_client, "non_existing_key", "$") is None
assert await json.get(redis_client, key, "$.d") == "[]"

@pytest.mark.parametrize("cluster_mode", [True, False])
Expand All @@ -50,18 +49,18 @@ async def test_json_set_get_multiple_values(self, redis_client: TRedisClient):
redis_client,
key,
"$",
OuterJson.dumps({"a": {"c": 1, "d": 4}, "b": {"c": 2}, "c": 3}),
OuterJson.dumps({"a": {"c": 1, "d": 4}, "b": {"c": 2}, "c": True}),
)
== OK
)

result = await json.get(redis_client, key, "$..c")
assert isinstance(result, str)
assert OuterJson.loads(result) == [3, 1, 2]
assert OuterJson.loads(result) == [True, 1, 2]

result = await json.get(redis_client, key, ["$..c", "$.c"])
assert isinstance(result, str)
assert OuterJson.loads(result) == {"$..c": [3, 1, 2], "$.c": [3]}
assert OuterJson.loads(result) == {"$..c": [True, 1, 2], "$.c": [True]}

assert await json.set(redis_client, key, "$..c", '"new_value"') == OK
result = await json.get(redis_client, key, "$..c")
Expand Down Expand Up @@ -135,14 +134,14 @@ async def test_json_get_formatting(self, redis_client: TRedisClient):
)

result = await json.get(
redis_client, key, "$", indent=" ", newline="\n", space=" "
redis_client, key, "$", JsonGetOptions(indent=" ", newline="\n", space=" ")
)

expected_result = '[\n {\n "a": 1.0,\n "b": 2,\n "c": {\n "d": 3,\n "e": 4\n }\n }\n]'
assert result == expected_result

result = await json.get(
redis_client, key, "$", indent="~", newline="\n", space="*"
redis_client, key, "$", JsonGetOptions(indent="~", newline="\n", space="*")
)

expected_result = (
Expand Down
22 changes: 0 additions & 22 deletions python/python/tests/tests_redis_modules/test_redis_modules.py

This file was deleted.

0 comments on commit e3633d9

Please sign in to comment.