Skip to content

Commit 5bafca5

Browse files
committed
Add section on array length to native PG JSON vs EQL docs
1 parent cf84ced commit 5bafca5

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

NATIVE_POSTGRES_JSON_COMPARED_TO_EQL.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,3 +403,57 @@ WHERE EXISTS (
403403
"q": "ste_vec"
404404
}
405405
```
406+
407+
## `json_array_length` and `jsonb_array_length`
408+
409+
### Native Postgres JSON(B)
410+
411+
```sql
412+
-- Both of these examples return the int `3`.
413+
-- The only difference is the input type.
414+
SELECT json_array_length('[1, 2, 3]');
415+
SELECT jsonb_array_length('[1, 2, 3]');
416+
```
417+
418+
### EQL
419+
420+
The Postgres `array_length` function can be used with `cs_ste_vec_terms_v1` to find the length of an array.
421+
422+
The eJSONPath used with `cs_ste_vec_terms_v1` needs to end with `[*]` (`$.some_array_field[*]` for example).
423+
424+
> [!IMPORTANT]
425+
> Determining array length with `cs_ste_vec_terms_v1` only works when the given eJSONPath only matches a single array.
426+
> Attempting to determine array length using `cs_ste_vec_terms_v1` when the eJSONPath matches multiple arrays (for example, when there are nested arrays or multiple arrays at the same depth) can return unexpected results.
427+
428+
Example query:
429+
430+
```sql
431+
SELECT COALESCE( -- We `COALESCE` because cs_ste_vec_terms_v1 will return `NULL` for empty arrays.
432+
array_length( -- `cs_ste_vec_terms_v1` returns an array type (not JSON(B)), so we use `array_length`.
433+
cs_ste_vec_terms_v1(encrypted_jsonb, $1), -- Pluck out the array of terms at the path in $1.
434+
1 -- The array dimension to find the length of (term array are flat, so this should always be 1).
435+
),
436+
0 -- Assume a length of `0` when `cs_ste_vec_terms_v1` returns `NULL`.
437+
) AS len FROM examples;
438+
```
439+
440+
Example data and params:
441+
442+
```javascript
443+
// Assume that examples.encrypted_jsonb has JSON objects with the shape:
444+
{
445+
"val": [1, 2, 3]
446+
}
447+
448+
// `$1` is the EQL plaintext payload for the eJSONPath `$.val[*]`:
449+
{
450+
"k": "pt",
451+
"p": "$.val[*]",
452+
"i": {
453+
"t": "examples",
454+
"c": "encrypted_jsonb"
455+
},
456+
"v": 1,
457+
"q": "ejson_path"
458+
}
459+
```

0 commit comments

Comments
 (0)