Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,12 +253,14 @@ JSON.ARRINDEX <key> <path> <json-scalar> [start [stop]]
Search for the first occurrence of a scalar JSON value in an array.

The optional inclusive `start` (default 0) and exclusive `stop` (default 0, meaning that the last element is included) specify a slice of the array to search.
Negative values are interpreted as starting from the end.


Note: out of range errors are treated by rounding the index to the array's start and end. An inverse index range (e.g. from 1 to 0) will return unfound.

#### Return value

[Integer][2], specifically the position of the scalar value in the array, or -1 if unfound.
[Array][4], specifically, for each JSON value matching the path, the first position of the scalar value in the array, -1 if unfound in the array, or [null][6] element if the matching JSON value is not an array.

### JSON.ARRINSERT

Expand Down Expand Up @@ -474,3 +476,4 @@ Return the JSON in `key` in [Redis Serialization Protocol (RESP)][5].
[3]: http://redis.io/topics/protocol#resp-bulk-strings
[4]: http://redis.io/topics/protocol#resp-arrays
[5]: http://redis.io/topics/protocol
[6]: https://redis.io/topics/protocol#null-elements-in-arrays
132 changes: 87 additions & 45 deletions src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::formatter::RedisJsonFormatter;
use crate::manager::{AddUpdateInfo, Manager, ReadHolder, SetUpdateInfo, UpdateInfo, WriteHolder};
use crate::redisjson::{Format, Path};
use crate::redisjson::{normalize_arr_indices, Format, Path};
use jsonpath_lib::select::select_value::{SelectValue, SelectValueType};
use redis_module::{Context, RedisValue};
use redis_module::{NextArg, RedisError, RedisResult, RedisString, REDIS_OK};
Expand Down Expand Up @@ -315,7 +315,7 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
}
}

pub fn is_eqaul<T1: SelectValue, T2: SelectValue>(&self, a: &T1, b: &T2) -> bool {
pub fn is_equal<T1: SelectValue, T2: SelectValue>(&self, a: &T1, b: &T2) -> bool {
match (a.get_type(), b.get_type()) {
(SelectValueType::Null, SelectValueType::Null) => true,
(SelectValueType::Bool, SelectValueType::Bool) => a.get_bool() == b.get_bool(),
Expand All @@ -327,7 +327,7 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
false
} else {
for (i, e) in a.values().unwrap().into_iter().enumerate() {
if !self.is_eqaul(e, b.get_index(i).unwrap()) {
if !self.is_equal(e, b.get_index(i).unwrap()) {
return false;
}
}
Expand All @@ -343,7 +343,7 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
let temp2 = b.get_key(k);
match (temp1, temp2) {
(Some(a1), Some(b1)) => {
if !self.is_eqaul(a1, b1) {
if !self.is_equal(a1, b1) {
return false;
}
}
Expand All @@ -360,51 +360,62 @@ impl<'a, V: SelectValue> KeyValue<'a, V> {
pub fn arr_index(
&self,
path: &str,
scalar_json: &str,
scalar_value: Value,
start: i64,
end: i64,
) -> Result<i64, Error> {
let res = self.get_first(path)?;
if res.get_type() == SelectValueType::Array {
// end=-1/0 means INFINITY to support backward with RedisJSON
if res.len().unwrap() == 0 || end < -1 {
return Ok(-1);
}
let v: Value = serde_json::from_str(scalar_json)?;
) -> Result<RedisValue, Error> {
let res = self
.get_values(path)?
.iter()
.map(|value| {
self.arr_first_index_single(value, &scalar_value, start, end)
.into()
})
.collect::<Vec<RedisValue>>();
Ok(res.into())
}

let len = res.len().unwrap() as i64;
pub fn arr_index_legacy(
&self,
path: &str,
scalar_value: Value,
start: i64,
end: i64,
) -> Result<RedisValue, Error> {
let arr = self.get_first(path)?;
Ok(
match self.arr_first_index_single(arr, &scalar_value, start, end) {
FoundIndex::NotArray => RedisValue::Integer(-1),
i => i.into(),
},
)
}

// Normalize start
let start = if start < 0 {
0.max(len + start)
} else {
// start >= 0
start.min(len - 1)
};
/// Returns first array index of `v` in `arr`, or NotFound if not found in `arr`, or NotArray if `arr` is not an array
fn arr_first_index_single(&self, arr: &V, v: &Value, start: i64, end: i64) -> FoundIndex {
if !arr.is_array() {
return FoundIndex::NotArray;
}

// Normalize end
let end = match end {
0 => len,
e if e < 0 => len + end,
_ => end.min(len),
};
let len = arr.len().unwrap() as i64;
if len == 0 {
return FoundIndex::NotFound;
}
// end=0 means INFINITY to support backward with RedisJSON
let (start, end) = normalize_arr_indices(start, end, len);

if end < start {
// don't search at all
return Ok(-1);
}
let mut i = -1;
for index in start..end {
if self.is_eqaul(res.get_index(index as usize).unwrap(), &v) {
i = index;
break;
}
}
if end < start {
// don't search at all
return FoundIndex::NotFound;
}

Ok(i)
} else {
Ok(-1)
for index in start..end {
if self.is_equal(arr.get_index(index as usize).unwrap(), v) {
return FoundIndex::Index(index);
}
}

FoundIndex::NotFound
}

pub fn obj_keys(&self, path: &str) -> Result<Box<dyn Iterator<Item = &'_ str> + '_>, Error> {
Expand Down Expand Up @@ -868,6 +879,22 @@ pub fn command_json_arr_append<M: Manager>(
}
}

enum FoundIndex {
Index(i64),
NotFound,
NotArray,
}

impl From<FoundIndex> for RedisValue {
fn from(e: FoundIndex) -> Self {
match e {
FoundIndex::NotFound => RedisValue::Integer(-1),
FoundIndex::NotArray => RedisValue::Null,
FoundIndex::Index(i) => RedisValue::Integer(i),
}
}
}

pub fn command_json_arr_index<M: Manager>(
manager: M,
ctx: &Context,
Expand All @@ -885,11 +912,26 @@ pub fn command_json_arr_index<M: Manager>(

let key = manager.open_key_read(ctx, &key)?;

let index = key.get_value()?.map_or(Ok(-1), |doc| {
KeyValue::new(doc).arr_index(path.get_path(), json_scalar, start, end)
})?;
let is_legacy = path.is_legacy();
let scalar_value: Value = serde_json::from_str(json_scalar)?;
if !is_legacy && (scalar_value.is_array() || scalar_value.is_object()) {
return Err(RedisError::String(format!(
"ERR expected scalar but found {}",
json_scalar
)));
}

let res = key
.get_value()?
.map_or(Ok(RedisValue::Integer(-1)), |doc| {
if path.is_legacy() {
KeyValue::new(doc).arr_index_legacy(path.get_path(), scalar_value, start, end)
} else {
KeyValue::new(doc).arr_index(path.get_path(), scalar_value, start, end)
}
})?;

Ok(index.into())
Ok(res)
}

pub fn command_json_arr_insert<M: Manager>(
Expand Down
8 changes: 2 additions & 6 deletions src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use redis_module::{Context, NotifyEvent, RedisString};

use std::marker::PhantomData;

use crate::redisjson::RedisJSON;
use crate::redisjson::{normalize_arr_start_index, RedisJSON};
use crate::Format;
use crate::REDIS_JSON_TYPE;

Expand Down Expand Up @@ -417,11 +417,7 @@ impl<'a> WriteHolder<Value, Value> for KeyHolderWrite<'a> {
}
// Verify legel index in bounds
let len = array.len() as i64;
let index = if index < 0 {
0.max(len + index)
} else {
index.min(len - 1)
} as usize;
let index = normalize_arr_start_index(index, len) as usize;

let mut new_value = v.take();
let curr = new_value.as_array_mut().unwrap();
Expand Down
39 changes: 25 additions & 14 deletions src/redisjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,33 @@ use crate::c_api::JSONType;
use crate::error::Error;
use crate::nodevisitor::{StaticPathElement, StaticPathParser, VisitStatus};

//use crate::normalize_arr_start_index;
use std::fmt;
use std::fmt::Display;

/// Returns normalized start index
pub fn normalize_arr_start_index(start: i64, len: i64) -> i64 {
Comment thread
oshadmi marked this conversation as resolved.
Resolved
if start < 0 {
0.max(len + start)
} else {
// start >= 0
start.min(len - 1)
}
}

/// Return normalized `(start, end)` indices as a tuple
pub fn normalize_arr_indices(start: i64, end: i64, len: i64) -> (i64, i64) {
// Normalize start
let start = normalize_arr_start_index(start, len);
// Normalize end
let end = match end {
0 => len,
e if e < 0 => len + end,
_ => end.min(len),
};
(start, end)
}

#[derive(Debug, PartialEq)]
pub enum SetOptions {
NotExists,
Expand Down Expand Up @@ -308,20 +332,7 @@ impl RedisJSON {

let len = arr.len() as i64;

// Normalize start
let start = if start < 0 {
0.max(len + start)
} else {
// start >= 0
start.min(len - 1)
};

// Normalize end
let end = match end {
0 => len,
e if e < 0 => len + end,
_ => end.min(len),
};
let (start, end) = normalize_arr_indices(start, end, len);

if end < start {
// don't search at all
Expand Down
9 changes: 9 additions & 0 deletions tests/pytest/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,7 @@ def testArrIndexCommand(env):
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', 0, 6), 6)
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', 0, 4, -0), 6)
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', 0, 5, -1), -1)
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', 0, 5, 0), 6)
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', 2, -2, 6), -1)
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', '"foo"'), -1)

Expand All @@ -600,6 +601,14 @@ def testArrIndexCommand(env):
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', 2, 3), 5)
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', '[4]'), 4)

r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '.arr', 1), 1)

r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '$.arr', 1), [1])
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '$.arr', 2, 1, 4), [2])
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '$.arr', 6), [-1])
r.assertEqual(r.execute_command('JSON.ARRINDEX', 'test', '$.arr', 3, 0, 2), [-1])


def testArrInsertCommand(env):
"""Test JSON.ARRINSERT command"""
r = env
Expand Down
2 changes: 1 addition & 1 deletion tests/pytest/test_keyspace_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def test_keyspace_arr(env):
assert_msg(env, pubsub.get_message(), 'pmessage', 'test_key_arr')

# Negative tests should not get an event
env.assertEqual(0, r.execute_command('JSON.ARRINDEX', 'test_key_arr', '$.foo', '"gogo1"'))
env.assertEqual([0], r.execute_command('JSON.ARRINDEX', 'test_key_arr', '$.foo', '"gogo1"'))
env.assertEqual(None, pubsub.get_message())

env.assertEqual(2, r.execute_command('JSON.ARRLEN', 'test_key_arr', '$.foo'))
Expand Down
Loading