JSON functions: JSON_EXTRACT, JSON_TABLE, JSON_SET and more
CoraDB stores JSON in the JSON data type and provides functions to build, read, search and change JSON values. A second group of functions returns vertices, edges and their neighborhoods as JSON, for graph queries.
| Group | Functions |
|---|---|
| Create | JSON_ARRAY, JSON_OBJECT, JSON_QUOTE |
| Inspect | JSON_KEYS, JSON_GET_ALL_PATHS, JSON_DEPTH, JSON_LENGTH, JSON_VALID, JSON_TYPE, JSON_UNQUOTE, JSON_PRETTY |
| Search and extract | JSON_SEARCH, JSON_EXTRACT, ->, ->>, JSON_CONTAINS_PATH, JSON_CONTAINS |
| Modify | JSON_MERGE_PATCH, JSON_MERGE_PRESERVE, JSON_MERGE, JSON_ARRAY_APPEND, JSON_ARRAY_INSERT, JSON_INSERT, JSON_SET, JSON_REPLACE, JSON_REMOVE |
| Rows from JSON | JSON_TABLE |
| Graph elements as JSON | JSON_PROPERTIES, JSON_NODE_PROPERTIES, JSON_EDGE_PROPERTIES, JSON_INFO, JSON_GRAPH, JSON_ADJACENCY_LIST, JSON_TOPOLOGY_RECORD, JSON_GRAPH_HEAP_MEMORY_USAGE |
The aggregate functions JSON_ARRAYAGG and JSON_OBJECTAGG build JSON arrays and objects from groups of rows.
Arguments
Section titled “Arguments”The functions share these kinds of arguments:
- json_doc: a JSON value, or a string that is parsed as JSON.
- val: a JSON value, or a value that is converted to a JSON scalar.
- json key: a string used as an object key.
- json path: a path such as
'$.a[0]', following the rules in JSON paths and JSON pointers.
How a json_doc and a val argument accept other SQL types:
| Input type | As json_doc | As val |
|---|---|---|
| JSON | Used as is | Used as is |
| String | Parsed as JSON | Converted to a JSON string |
| SHORT, INTEGER | Conversion error | Converted to a JSON integer |
| BIGINT | Conversion error | Converted to a JSON bigint |
| FLOAT, DOUBLE, NUMERIC | Conversion error | Converted to a JSON double |
| NULL | NULL | Converted to JSON null |
| Other | Conversion error | Conversion error |
String arguments are processed as UTF-8; strings in other character sets are converted first.
JSON_ARRAY
Section titled “JSON_ARRAY”JSON_ARRAY ([val1 [ , val2] ...])The JSON_ARRAY function returns a json array containing the given list (possibly empty) of values.
SELECT JSON_ARRAY();| JSON_ARRAY() |
|---|
| [] |
SELECT JSON_ARRAY(1, '1', json '{"a":4}', json '[1,2,3]');| JSON_ARRAY(1, '1', json '{"a":4}', json '[1,2,3]') |
|---|
| [1,"1",{"a":4},[1,2,3]] |
JSON_OBJECT
Section titled “JSON_OBJECT”JSON_OBJECT ([key1, val1 [ , key2, val2] ...])The JSON_OBJECT function returns a json object containing the given list (possibly empty) of key-value pairs.
SELECT JSON_OBJECT();| JSON_OBJECT() |
|---|
| {} |
SELECT JSON_OBJECT('a', 1, 'b', '1', 'c', json '{"a":4}', 'd', json '[1,2,3]');| JSON_OBJECT('a', 1, 'b', '1', 'c', json '{"a":4}', 'd', json '[1,2,3]') |
|---|
| {"a":1,"b":"1","c":{"a":4},"d":[1,2,3]} |
JSON_KEYS
Section titled “JSON_KEYS”JSON_KEYS (json_doc [ , json path])The JSON_KEYS function returns a json array of all the object keys of the json object at the given path. Json null is returned if the path addresses a json element that is not a json object. If json path argument is missing, the keys are gathered from json root element. An error occurs if json path does not exist. Returns NULL if json_doc argument is NULL.
SELECT JSON_KEYS('{}');| JSON_KEYS('{}') |
|---|
| [] |
SELECT JSON_KEYS('"non-object"');| JSON_KEYS('"non-object"') |
|---|
| null |
SELECT JSON_KEYS('{"a":1, "b":2, "c":{"d":1}}');| JSON_KEYS('{"a":1, "b":2, "c":{"d":1}}') |
|---|
| ["a","b","c"] |
JSON_GET_ALL_PATHS
Section titled “JSON_GET_ALL_PATHS”JSON_GET_ALL_PATHS (json_doc)Returns a JSON array with the path of every element of json_doc, including the root $. Object keys are written in double quotes ($."a"), and the paths of an element's children come before the path of the element itself. Returns NULL if the argument is NULL.
SELECT JSON_GET_ALL_PATHS('[1, [2, 3]]');| JSON_GET_ALL_PATHS('[1, [2, 3]]') |
|---|
| ["$[0]","$[1][0]","$[1][1]","$[1]","$"] |
SELECT JSON_GET_ALL_PATHS('{"a":["a","b"],"b":"a","c":{"d":1}}');| JSON_GET_ALL_PATHS('{"a":["a","b"],"b":"a","c":{"d":1}}') |
|---|
["$.\"a\"[0]","$.\"a\"[1]","$.\"a\"","$.\"b\"","$.\"c\".\"d\"","$.\"c\"","$"] |
A scalar has only the root path:
SELECT JSON_GET_ALL_PATHS('"scalar"');| JSON_GET_ALL_PATHS('"scalar"') |
|---|
| ["$"] |
JSON_DEPTH
Section titled “JSON_DEPTH”JSON_DEPTH (json_doc)The JSON_DEPTH function returns the maximum depth of the json. Depth count starts at 1. The depth level is increased by one by non-empty json arrays or by non-empty json objects. Returns NULL if argument is NULL.
SELECT JSON_DEPTH('"scalar"');| JSON_DEPTH('"scalar"') |
|---|
| 1 |
SELECT JSON_DEPTH('[{"a":4}, 2]');| JSON_DEPTH('[{"a":4}, 2]') |
|---|
| 3 |
Example of a deeper json:
SELECT JSON_DEPTH('[{"a":[1,2,3,{"k":[4,5]}]},2,3,4,5,6,7]');| JSON_DEPTH('[{"a":[1,2,3,{"k":[4,5]}]},2,3,4,5,6,7]') |
|---|
| 6 |
JSON_LENGTH
Section titled “JSON_LENGTH”JSON_LENGTH (json_doc [ , json path])The JSON_LENGTH function returns the length of the json element at the given path. If no path argument is given, the returned value is the length of the root json element. Returns NULL if any argument is NULL or if no element exists at the given path.
SELECT JSON_LENGTH('"scalar"');| JSON_LENGTH('"scalar"') |
|---|
| 1 |
SELECT JSON_LENGTH('[{"a":4}, 2]', '$.a');| JSON_LENGTH('[{"a":4}, 2]', '$.a') |
|---|
| NULL |
SELECT JSON_LENGTH('[2, {"a":4, "b":4, "c":4}]', '$[1]');| JSON_LENGTH('[2, {"a":4, "b":4, "c":4}]', '$[1]') |
|---|
| 3 |
SELECT JSON_LENGTH('[{"a":[1,2,3,{"k":[4,5,6,7,8]}]},2]');| JSON_LENGTH('[{"a":[1,2,3,{"k":[4,5,6,7,8]}]},2]') |
|---|
| 2 |
JSON_VALID
Section titled “JSON_VALID”JSON_VALID (val)The JSON_VALID function returns 1 if the given val argument is a valid json_doc, 0 otherwise. Returns NULL if argument is NULL.
SELECT JSON_VALID('[{"a":4}, 2]'), JSON_VALID('{"wrong json object":');| JSON_VALID('[{"a":4}, 2]') | JSON_VALID('{"wrong json object":') |
|---|---|
| 1 | 0 |
JSON_TYPE
Section titled “JSON_TYPE”JSON_TYPE (json_doc)The JSON_TYPE function returns the type of the json_doc argument as a string: JSON_ARRAY, JSON_OBJECT, STRING, INTEGER, DOUBLE, BOOLEAN or JSON_NULL.
SELECT JSON_TYPE('[{"a":4}, 2]'), JSON_TYPE('{"a":4}'), JSON_TYPE('"aaa"'), JSON_TYPE('12'), JSON_TYPE('1.5'), JSON_TYPE('true'), JSON_TYPE('null');| JSON_TYPE('[{"a":4}, 2]') | JSON_TYPE('{"a":4}') | JSON_TYPE('"aaa"') | JSON_TYPE('12') | JSON_TYPE('1.5') | JSON_TYPE('true') | JSON_TYPE('null') |
|---|---|---|---|---|---|---|
| JSON_ARRAY | JSON_OBJECT | STRING | INTEGER | DOUBLE | BOOLEAN | JSON_NULL |
JSON_QUOTE
Section titled “JSON_QUOTE”JSON_QUOTE (str)Escapes quotes and special characters and surrounds the resulting string in quotes. Returns result as a json_string. Returns NULL if str argument is NULL.
SELECT JSON_QUOTE ('simple');| JSON_QUOTE ('simple') |
|---|
| "simple" |
SELECT JSON_QUOTE('"');| JSON_QUOTE('"') |
|---|
"\"" |
JSON_UNQUOTE
Section titled “JSON_UNQUOTE”JSON_UNQUOTE (json_doc)Unquotes a json_value's json string and returns the resulting string. Returns NULL if json_doc argument is NULL.
Escape sequences such as \" and \uXXXX are decoded:
SELECT JSON_UNQUOTE('"\""');| JSON_UNQUOTE('"\""') |
|---|
| " |
JSON_PRETTY
Section titled “JSON_PRETTY”JSON_PRETTY (json_doc)Returns a string containing the json_doc pretty-printed. Returns NULL if json_doc argument is NULL.
SELECT JSON_PRETTY('[{"a":"val1", "b":"val2", "c": [1, "elem2", 3, 4, {"key":"val"}]}]');[ { "a": "val1", "b": "val2", "c": [ 1, "elem2", 3, 4, { "key": "val" } ] }]JSON_SEARCH
Section titled “JSON_SEARCH”JSON_SEARCH (json_doc, one/all, search_str [, escape_char [, json path] ...])Returns a json array of json paths or a single json path which contain json strings matching the given search_str. The matching is performed by applying the LIKE operator on internal json strings and search_str. Same rules apply for the escape_char and search_str of JSON_SEARCH as for their counter-parts from the LIKE operator. For further description of LIKE-related arguments rules refer to LIKE.
Using 'one' as one/all argument will cause the JSON_SEARCH to stop after the first match is found. On the other hand, 'all' will force JSON_SEARCH to gather all paths matching the given search_str.
The given json paths determine filters on the returned paths, the resulting json paths's prefixes need to match at least one given json path argument. If no json path argument is given, JSON_SEARCH will execute the search starting from the root element.
SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'one', 'a');| JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'one', 'a') |
|---|
| $.a[0] |
SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a');| JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a') |
|---|
| ["$.a[0]","$.b","$.c"] |
SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.a', '$.b');| JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.a', '$.b') |
|---|
| ["$.a[0]","$.b"] |
Wildcards can be used to define path filters as more general formats. Accepting only json paths that start with object key identifier:
SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.*');| JSON_SEARCH('{"a":["a","b"],"b":"a","c":"a"}', 'all', 'a', NULL, '$.*') |
|---|
| ["$.a[0]","$.b","$.c"] |
Accepting only json paths that start with object key identifier and follow immediately with a json array index will filter out '$.b', '$.d.e[0]' matches:
SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$.*[*]');| JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$.[]') |
|---|
| ["$.a[0]","$.c[0]"] |
Accepting any paths that contain json array indexes will filter out '$.b'
SELECT JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$**[*]');| JSON_SEARCH('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', 'all', 'a', NULL, '$**[*]') |
|---|
| ["$.a[0]","$.c[0]","$.d.e[0]"] |
JSON_EXTRACT
Section titled “JSON_EXTRACT”JSON_EXTRACT (json_doc, json path [, json path] ...)Returns json elements from the json_doc, that are addressed by the given paths. If json path arguments contain wildcards, all elements that are addressed by a path compatible with the wildcards-containing json path are gathered in a resulting json array. A single json element is returned if no wildcards are used in the given json paths and a single element is found, otherwise the json elements found are wrapped in a json array. Raises an error if a json path is NULL or invalid or if json_doc argument is invalid. Returns NULL if no elements are found or if json_doc is NULL.
SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a');| JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a') |
|---|
| ["a","b"] |
SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a[*]');| JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.a[*]') |
|---|
| ["a","b"] |
Changing '.a' from previous query with '.*' wildcards will also match '$.c[0]'. This will match any json path that is exactly an object key identifier followed by an array index.
SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.*[*]');| JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.[]') |
|---|
| ["a","b","a"] |
The following json path will match all json paths that end with a json array index (matches all previous matched paths and, in addition, '$.d.e[0]')
SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$**[*]');| JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$**[*]') |
|---|
| ["a","b","a","a"] |
SELECT JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.d**[*]');| JSON_EXTRACT('{"a":["a","b"],"b":"a","c":["a"], "d":{"e":["a"]}}', '$.d**[*]') |
|---|
| ["a"] |
-> operator
Section titled “-> operator”column -> json_pathShort form of JSON_EXTRACT(column, json_path). The left operand must be a column (of a table, a view or a derived table). It raises an error if json_path is NULL or invalid, and returns NULL when the column value is NULL.
->> operator
Section titled “->> operator”column ->> json_pathShort form of JSON_UNQUOTE(JSON_EXTRACT(column, json_path)): it returns the value as a string, without the quotes of a JSON string.
The e-commerce tables have no JSON column, so this example builds one in a derived table with JSON_OBJECT. Note that the NUMERIC price becomes a JSON double:
SELECT t.j, t.j->'$.name' AS name_json, t.j->>'$.name' AS name_text, t.j->'$.price' AS priceFROM (SELECT JSON_OBJECT('id', id, 'name', name, 'price', unit_price) AS j FROM product WHERE id < 3) tORDER BY 1;| j | name_json | name_text | price |
|---|---|---|---|
| {"id":1,"name":"Chai","price":18.0} | Chai | Chai | 18.0 |
| {"id":2,"name":"Chang","price":19.0} | Chang | Chang | 19.0 |
name_json is the JSON string "Chai" (shown without quotes, see the note at the top of the page); name_text is the plain string Chai.
JSON_CONTAINS_PATH
Section titled “JSON_CONTAINS_PATH”JSON_CONTAINS_PATH (json_doc, one/all, json path [, json path] ...)The JSON_CONTAINS_PATH function verifies whether the given paths exist inside the json_doc.
When one/all argument is 'all', all given paths must exist to return 1. Returns 0 otherwise.
When one/all argument is 'one', it returns 1 if any given path exists. Returns 0 otherwise.
Returns NULL if any argument is NULL. An error occurs if any argument is invalid.
SELECT JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]');| JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]') |
|---|
| 1 |
SELECT JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]', '$.inexistent');| JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'all', '$[0]', '$[0]."0"', '$[1]', '$[2]', '$[3]', '$.inexistent') |
|---|
| 0 |
The JSON_CONTAINS_PATH function supports wildcards inside json paths.
SELECT JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'one', '$.inexistent', '$[*]."three"');| JSON_CONTAINS_PATH ('[{"0":0},1,"2",{"three":3}]', 'one', '$.inexistent', '$[*]."three"') |
|---|
| 1 |
JSON_CONTAINS
Section titled “JSON_CONTAINS”JSON_CONTAINS (json_doc doc1, json_doc doc2 [, json path])The JSON_CONTAINS function verifies whether the doc2 is contained inside the doc1 at the optionally specified path. A json element contains another json element if the following recursive rules are satisfied:
- A json scalar contains another json scalar if they have the same type (their JSON_TYPE () are equal) and are equal. As an exception, json integer can be compared and equal to json double (even if their JSON_TYPE () evaluation are different).
- A json array contains a json scalar or a json object if any of json array's elements contains the json_nonarray.
- A json array contains another json array if all the second json array's elements are contained in the first json array.
- A json object contains another json object if, for every (key2, value2) pair in the second object, there exists a (key1, value1) pair in the first object with key1 = key2 and value2 contained in value1.
- Otherwise the json element is not contained.
Returns whether doc2 is contained in root json element of doc1 if no json path argument is given. Returns NULL if any argument is NULL. An error occurs if any argument is invalid.
SELECT JSON_CONTAINS ('"simple"','"simple"');| JSON_CONTAINS ('"simple"','"simple"') |
|---|
| 1 |
SELECT JSON_CONTAINS ('["a", "b"]','"b"');| JSON_CONTAINS ('["a", "b"]','"b"') |
|---|
| 1 |
SELECT JSON_CONTAINS ('["a", "b1", ["a", "b2"]]','["b1", "b2"]');| JSON_CONTAINS ('["a", "b1", ["a", "b2"]]','["b1", "b2"]') |
|---|
| 1 |
SELECT JSON_CONTAINS ('{"k1":["a", "b1"], "k2": ["a", "b2"]}','{"k1":"b1", "k2":"b2"}');| JSON_CONTAINS ('{"k1":["a", "b1"], "k2": ["a", "b2"]}','{"k1":"b1", "k2":"b2"}') |
|---|
| 1 |
Note that json objects do not check containment the same way json arrays do. It is impossible to have a json element that is not a descendent of a json object contained in a sub-element of a json object.
SELECT JSON_CONTAINS ('["a", "b1", ["a", {"k":"b2"}]]','["b1", "b2"]');| JSON_CONTAINS ('["a", "b1", ["a", {"k":"b2"}]]','["b1", "b2"]') |
|---|
| 0 |
SELECT JSON_CONTAINS ('["a", "b1", ["a", {"k":["b2"]}]]','["b1", {"k":"b2"}]');| JSON_CONTAINS ('["a", "b1", ["a", {"k":["b2"]}]]','["b1", {"k":"b2"}]') |
|---|
| 1 |
JSON_MERGE_PATCH
Section titled “JSON_MERGE_PATCH”JSON_MERGE_PATCH (json_doc, json_doc [, json_doc] ...)The JSON_MERGE_PATCH function merges two or more json docs and returns the resulting merged json. JSON_MERGE_PATCH differs from JSON_MERGE_PRESERVE in that it will take the second argument when encountering merging conflicts. JSON_MERGE_PATCH is compliant with RFC 7396.
The merging of two json documents is performed with the following rules, recursively:
- When two non-object jsons are merged, the result of the merge is the second value.
- When a non-object json is merged with a json object, the result is the merge of an empty object with the second merging argument.
- When two objects are merged, the resulting object consists of the following members:
- All members from the first object that have no corresponding member with the same key in the second object.
- All members from the second object that have no corresponding members with equal keys in the first object, having values not null. Members with null values from second object are ignored.
- One member for each member in the first object that has a corresponding non-null valued member in the second object with the same key. Same key members that appear in both objects and the second object's member value is null, are ignored. The values of these pairs become the results of merging operations performed on the values of the members from the first and second object.
Merge operations are executed serially when there are more than two arguments: the result of merging first two arguments is merged with third, this result is then merged with fourth and so on.
Returns NULL if any argument is NULL. An error occurs if any argument is not valid.
SELECT JSON_MERGE_PATCH ('["a","b","c"]', '"scalar"');| JSON_MERGE_PATCH ('["a","b","c"]', '"scalar"') |
|---|
| scalar |
The exception to the merge-patching, when the first argument is non-object and the second is an object. A merge operation is performed between an empty object and the second object argument.
SELECT JSON_MERGE_PATCH ('["a"]', '{"a":null}');| JSON_MERGE_PATCH ('["a"]', '{"a":null}') |
|---|
| {} |
Objects merging example, exemplifying the described object merging rules:
SELECT JSON_MERGE_PATCH ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}');| JSON_MERGE_PATCH ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}') |
|---|
| {"a":null,"c":{},"d":"elem"} |
JSON_MERGE_PRESERVE
Section titled “JSON_MERGE_PRESERVE”JSON_MERGE_PRESERVE (json_doc, json_doc [, json_doc] ...)The JSON_MERGE_PRESERVE function merges two or more json docs and returns the resulting merged json. JSON_MERGE_PRESERVE differs from JSON_MERGE_PATCH in that it preserves both json elements on merging conflicts.
The merging of two json documents is performed after the following rules, recursively:
- When two json arrays are merged, they are concatenated.
- When two non-array (scalar/object) json elements are merged and at most one of them is a json object, the result is an array containing the two json elements.
- When a non-array json element is merged with a json array, the non-array is wrapped as a single element json array and then merged with the json array according to json array merging rules.
- When two json objects are merged, all pairs that do not have a corresponding pair in the other json object are preserved. For matching keys, the values are always merged by applying the rules recursively.
Merge operations are executed serially when there are more than two arguments: the result of merging first two arguments is merged with third, this result is then merged with fourth and so on.
Returns NULL if any argument is NULL. An error occurs if any argument is not valid.
SELECT JSON_MERGE_PRESERVE ('"a"', '"b"');| JSON_MERGE_PRESERVE ('"a"', '"b"') |
|---|
| ["a","b"] |
SELECT JSON_MERGE_PRESERVE ('["a","b","c"]', '"scalar"');| JSON_MERGE_PRESERVE ('["a","b","c"]', '"scalar"') |
|---|
| ["a","b","c","scalar"] |
JSON_MERGE_PRESERVE, as opposed to JSON_MERGE_PATCH, will not drop and patch first argument's elements during merges and will gather them together.
SELECT JSON_MERGE_PRESERVE ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}');| JSON_MERGE_PRESERVE ('{"a":null,"c":["elem"]}','{"b":null,"c":{"k":null},"d":"elem"}') |
|---|
| {"a":null,"c":["elem",{"k":null}],"b":null,"d":"elem"} |
JSON_MERGE
Section titled “JSON_MERGE”JSON_MERGE (json_doc, json_doc [, json_doc] ...)JSON_MERGE is an alias for JSON_MERGE_PRESERVE.
JSON_ARRAY_APPEND
Section titled “JSON_ARRAY_APPEND”JSON_ARRAY_APPEND (json_doc, json path, json_val [, json path, json_val] ...)The JSON_ARRAY_APPEND function returns a modified copy of the first argument. For each given <json path, json_val> pair, the function appends the value to the json array addressed by the corresponding path.
The (json path, json_val) pairs are evaluated one by one, from left to right. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
If the json path points to a json array inside the json_doc, the json_val is appended at the end of the array. If the json path points to a non-array json element, the non-array gets wrapped as a single element json array containing the referred non-array element followed by the appending of the given json_val.
Returns NULL if any argument is NULL. An error occurs if any argument is invalid.
SELECT JSON_ARRAY_APPEND ('{"a":[1,2]}','$.a','b');| JSON_ARRAY_APPEND ('{"a":[1,2]}','$.a','b') |
|---|
| {"a":[1,2,"b"]} |
SELECT JSON_ARRAY_APPEND ('{"a":1}','$.a','b');| JSON_ARRAY_APPEND ('{"a":1}','$.a','b') |
|---|
| {"a":[1,"b"]} |
SELECT JSON_ARRAY_APPEND ('{"a":[1,2]}', '$.a[0]', '1');| JSON_ARRAY_APPEND ('{"a":[1,2]}', '$.a[0]', '1') |
|---|
| {"a":[[1,"1"],2]} |
JSON_ARRAY_INSERT
Section titled “JSON_ARRAY_INSERT”JSON_ARRAY_INSERT (json_doc, json path, json_val [, json path, json_val] ...)The JSON_ARRAY_INSERT function returns a modified copy of the first argument. For each given <json path, json_val> pair, the function inserts the value in the json array addressed by the corresponding path.
The (json path, json_val) pairs are evaluated one by one, from left to right. The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
The rules of the JSON_ARRAY_INSERT operation are the following:
- If a json path addresses an element of a json_array, the given json_val is inserted at the specified index, shifting any following elements to the right.
- If the json path points to an array index after the end of an array, the array is filled with nulls after end of the array until the specified index and the json_val is inserted at the specified index.
- If the json path does not exist inside the json_doc, the last token of the json path is an array index and the json path without the last array index token would have pointed to an element inside the json_doc, the element found by the stripped json path is replaced with single element json array and the JSON_ARRAY_INSERT operation is performed with the original json path.
Returns NULL if any argument is NULL. An error occurs if any argument is invalid or if a json_path does not address a cell of an array inside the json_doc.
SELECT JSON_ARRAY_INSERT ('[0,1,2]', '$[0]', '1');| JSON_ARRAY_INSERT ('[0,1,2]', '$[0]', '1') |
|---|
| ["1",0,1,2] |
SELECT JSON_ARRAY_INSERT ('[0,1,2]', '$[5]', '1');| JSON_ARRAY_INSERT ('[0,1,2]', '$[5]', '1') |
|---|
| [0,1,2,null,null,"1"] |
Examples for JSON_ARRAY_INSERT's third rule.
SELECT JSON_ARRAY_INSERT ('{"a":4}', '$[5]', '1');| JSON_ARRAY_INSERT ('{"a":4}', '$[5]', '1') |
|---|
| [{"a":4},null,null,null,null,"1"] |
SELECT JSON_ARRAY_INSERT ('"a"', '$[5]', '1');| JSON_ARRAY_INSERT ('"a"', '$[5]', '1') |
|---|
| ["a",null,null,null,null,"1"] |
JSON_INSERT
Section titled “JSON_INSERT”JSON_INSERT (json_doc, json path, json_val [, json path, json_val] ...)The JSON_INSERT function returns a modified copy of the first argument. For each given <json path, json_val> pair, the function inserts the value if no other value exists at the corresponding path.
The insertion rules for JSON_INSERT are the following:
The json_val is inserted if the json path addresses one of the following json values inside the json_doc:
- An inexistent object member of an existing json object. A (key, value) pair is added to the json object with the key being json path's last element and the value being the json_val.
- An array index past of an existing json array's end. The array is filled with nulls after the initial end of the array and the json_val is inserted at the specified index.
The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
Returns NULL if any argument is NULL. An error occurs if any argument is invalid.
Paths to existing elements inside the json_doc are ignored:
SELECT JSON_INSERT ('{"a":1}','$.a','b');| JSON_INSERT ('{"a":1}','$.a','b') |
|---|
| {"a":1} |
SELECT JSON_INSERT ('{"a":1}','$.b','1');| JSON_INSERT ('{"a":1}','$.b','1') |
|---|
| {"a":1,"b":"1"} |
SELECT JSON_INSERT ('[0,1,2]','$[4]','1');| JSON_INSERT ('[0,1,2]','$[4]','1') |
|---|
| [0,1,2,null,"1"] |
JSON_SET
Section titled “JSON_SET”JSON_SET (json_doc, json path, json_val [, json path, json_val] ...)The JSON_SET function returns a modified copy of the first argument. For each given <json path, json_val> pair, the function inserts or replaces the value at the corresponding path. Otherwise, the json_val is inserted if the json path addresses one of the following json values inside the json_doc:
- An inexistent object member of an existing json object. A (key, value) pair is added to the json object with the key deduced from the json path and the value being the json_val.
- An array index past of an existing json array's end. The array is filled with nulls after the initial end of the array and the json_val is inserted at the specified index.
The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
Returns NULL if any argument is NULL. An error occurs if any argument is invalid.
SELECT JSON_SET ('{"a":1}','$.a','b');| JSON_SET ('{"a":1}','$.a','b') |
|---|
| {"a":"b"} |
SELECT JSON_SET ('{"a":1}','$.b','1');| JSON_SET ('{"a":1}','$.b','1') |
|---|
| {"a":1,"b":"1"} |
SELECT JSON_SET ('[0,1,2]','$[4]','1');| JSON_SET ('[0,1,2]','$[4]','1') |
|---|
| [0,1,2,null,"1"] |
JSON_REPLACE
Section titled “JSON_REPLACE”JSON_REPLACE (json_doc, json path, json_val [, json path, json_val] ...)The JSON_REPLACE function returns a modified copy of the first argument. For each given <json path, json_val> pair, the function replaces the value only if another value is found at the corresponding path.
If the json_path does not exist inside the json_doc, the (json path, json_val) pair is ignored and has no effect.
The document produced by evaluating one pair becomes the new value against which the next pair is evaluated.
Returns NULL if any argument is NULL. An error occurs if any argument is invalid.
SELECT JSON_REPLACE ('{"a":1}','$.a','b');| JSON_REPLACE ('{"a":1}','$.a','b') |
|---|
| {"a":"b"} |
No replacement is done if the json path` does not exist inside the json_doc.
SELECT JSON_REPLACE ('{"a":1}','$.b','1');| JSON_REPLACE ('{"a":1}','$.b','1') |
|---|
| {"a":1} |
SELECT JSON_REPLACE ('[0,1,2]','$[4]','1');| JSON_REPLACE ('[0,1,2]','$[4]','1') |
|---|
| [0,1,2] |
JSON_REMOVE
Section titled “JSON_REMOVE”JSON_REMOVE (json_doc, json path [, json path] ...)The JSON_REMOVE function returns a modified copy of the first argument, by removing values from all given paths.
The json path arguments are evaluated one by one, from left to right. The result produced by evaluating a json path becomes the value against which the next json path is evaluated.
Returns NULL if any argument is NULL. An error occurs if any argument is invalid or if a path points to the root or if a path does not exist.
SELECT JSON_REMOVE ('[0,1,2]','$[1]');| JSON_REMOVE ('[0,1,2]','$[1]') |
|---|
| [0,2] |
SELECT JSON_REMOVE ('{"a":1,"b":2}','$.a');| JSON_REMOVE ('{"a":1,"b":2}','$.a') |
|---|
| {"b":2} |
JSON_TABLE
Section titled “JSON_TABLE”JSON_TABLE turns JSON into rows and columns that can be queried like a table, for example one row per element of a JSON array.
JSON_TABLE ( expr, path COLUMNS (column_list)) [AS] alias
column_list ::= column [, column] ...
column ::= name FOR ORDINALITY | name type PATH string_path [on_empty] [on_error] | name type EXISTS PATH string_path | NESTED [PATH] string_path COLUMNS (column_list)
on_empty ::= { NULL | ERROR | DEFAULT value } ON EMPTYon_error ::= { NULL | ERROR | DEFAULT value } ON ERROR- expr is the JSON document: a constant, a column, or the result of a function. It can refer to columns of tables listed before JSON_TABLE in the
FROMclause. - path selects the values that produce rows; each value found becomes one row. The alias is required.
- The COLUMNS clause defines the output columns:
- name FOR ORDINALITY: the row number within the current COLUMNS clause, starting at 1 (type INTEGER).
- name type PATH string_path: the value at string_path (relative to the row's value), converted to type. If the path is missing, the ON EMPTY clause applies; if the value cannot be converted, the ON ERROR clause applies. The default for both is NULL; ERROR raises an error and DEFAULT value uses value.
- name type EXISTS PATH string_path: 1 if the path exists, otherwise 0.
- NESTED [PATH] string_path COLUMNS (...): expands the values found at string_path into further rows, combined with the parent row like a nested loop. The same rules apply recursively.
Each element of $.a becomes a row. The second element, [2,3], cannot be converted to INT, so the default NULL ON ERROR applies:
SELECT * FROM JSON_TABLE('{"a":[1,[2,3]]}', '$.a[*]' COLUMNS (col INT PATH '$')) AS jt;| col |
|---|
| 1 |
| NULL |
With DEFAULT ... ON ERROR, the default value replaces it:
SELECT * FROM JSON_TABLE('{"a":[1,[2,3]]}', '$.a[*]' COLUMNS (col INT PATH '$' DEFAULT '-1' ON ERROR)) AS jt;| col |
|---|
| 1 |
| -1 |
Missing paths, ON EMPTY and EXISTS PATH:
SELECT * FROM JSON_TABLE('{"a":1}', '$' COLUMNS (col1 INT PATH '$.a', col2 INT PATH '$.b', col3 INT PATH '$.c' DEFAULT '0' ON EMPTY)) AS jt;| col1 | col2 | col3 |
|---|---|---|
| 1 | NULL | 0 |
SELECT * FROM JSON_TABLE('{"a":1,"b":[1]}', '$' COLUMNS (has_a INT EXISTS PATH '$.a', has_z INT EXISTS PATH '$.z')) AS jt;| has_a | has_z |
|---|---|
| 1 | 0 |
NESTED PATH
Section titled “NESTED PATH”Here '$.*' produces one parent row for each member value of the root object, and NESTED PATH '$[*]' expands each value that is an array. The nested ordinality column restarts at 1 for every parent row. The value 6 is not an array, so its nested columns are NULL:
SELECT * FROM JSON_TABLE( '{"a":[1,2],"b":[3,4,5],"d":6,"c":[7]}', '$.*' COLUMNS (ord FOR ORDINALITY, col JSON PATH '$', NESTED PATH '$[*]' COLUMNS (nested_ord FOR ORDINALITY, nested_col JSON PATH '$'))) AS jt;| ord | col | nested_ord | nested_col |
|---|---|---|---|
| 1 | [1,2] | 1 | 1 |
| 1 | [1,2] | 2 | 2 |
| 2 | [3,4,5] | 1 | 3 |
| 2 | [3,4,5] | 2 | 4 |
| 2 | [3,4,5] | 3 | 5 |
| 3 | 6 | NULL | NULL |
| 4 | [7] | 1 | 7 |
Sibling NESTED PATH clauses are processed one after the other: while one of them produces rows, the columns of the others are NULL. In the second parent row, $.key1 is the scalar 6, so $.key1[*] produces no rows:
SELECT * FROM JSON_TABLE( '{"a":{"key1":[1,2], "key2":[3,4,5]},"b":{"key1":6, "key2":[7]}}', '$.*' COLUMNS (ord FOR ORDINALITY, col JSON PATH '$', NESTED PATH '$.key1[*]' COLUMNS (nested_ord1 FOR ORDINALITY, nested_col1 JSON PATH '$'), NESTED PATH '$.key2[*]' COLUMNS (nested_ord2 FOR ORDINALITY, nested_col2 JSON PATH '$'))) AS jt;| ord | col | nested_ord1 | nested_col1 | nested_ord2 | nested_col2 |
|---|---|---|---|---|---|
| 1 | {"key1":[1,2],"key2":[3,4,5]} | 1 | 1 | NULL | NULL |
| 1 | {"key1":[1,2],"key2":[3,4,5]} | 2 | 2 | NULL | NULL |
| 1 | {"key1":[1,2],"key2":[3,4,5]} | NULL | NULL | 1 | 3 |
| 1 | {"key1":[1,2],"key2":[3,4,5]} | NULL | NULL | 2 | 4 |
| 1 | {"key1":[1,2],"key2":[3,4,5]} | NULL | NULL | 3 | 5 |
| 2 | {"key1":6,"key2":[7]} | NULL | NULL | 1 | 7 |
JSON_TABLE over table rows
Section titled “JSON_TABLE over table rows”expr can use the columns of a table that comes before JSON_TABLE in the FROM clause; JSON_TABLE is then evaluated once per row:
SELECT p.id, jt.*FROM product p, JSON_TABLE(JSON_OBJECT('name', p.name, 'stock', p.units_in_stock), '$' COLUMNS (name VARCHAR(64) PATH '$.name', stock INT PATH '$.stock', missing INT PATH '$.x' DEFAULT '0' ON EMPTY)) AS jtWHERE p.id < 3ORDER BY p.id;| id | name | stock | missing |
|---|---|---|---|
| 1 | Chai | 39 | 0 |
| 2 | Chang | 17 | 0 |
JSON functions for graph elements
Section titled “JSON functions for graph elements”These functions return vertices and edges matched by a MATCH pattern as JSON. Their argument is a vertex or edge alias of the pattern; the result is NULL when the argument is NULL.
Every vertex and edge is identified by its object identifier (OID), written as (volume|page|slot). OIDs depend on how the data was loaded, so the identifiers in your database will differ from the ones shown below.
The examples use product 1618 (Gobi HeatTec Tee), which is manufactured by the brand Diadora, belongs to a category and is available at a supplier.
JSON_PROPERTIES
Section titled “JSON_PROPERTIES”JSON_PROPERTIES (vertex_or_edge)Returns a JSON object with the OID of the element (id) and its column values (properties). NUMERIC values become JSON doubles; DATETIME values are written as strings.
SELECT JSON_PROPERTIES(p) AS props FROM MATCH (p:product) WHERE p.id = 1618;{"id":"(0|4490|63)","properties":{"id":1618,"units_in_stock":22,"unit_price":29.0,"description":"Size XL, Black","name":"Gobi HeatTec Tee"}}JSON_NODE_PROPERTIES
Section titled “JSON_NODE_PROPERTIES”JSON_NODE_PROPERTIES (vertex)The same as JSON_PROPERTIES, for a vertex.
SELECT JSON_NODE_PROPERTIES(b) AS v FROM MATCH (b:brand) WHERE b.name = 'Diadora';{"id":"(0|4545|52)","properties":{"id":52,"name":"Diadora"}}JSON_EDGE_PROPERTIES
Section titled “JSON_EDGE_PROPERTIES”JSON_EDGE_PROPERTIES (edge)The same as JSON_PROPERTIES, for an edge.
SELECT JSON_EDGE_PROPERTIES(m) AS eFROM MATCH (b:brand)-[m:manufactures]->(p:product)WHERE p.id = 1618;{"id":"(0|4931|461)","properties":{"since":"06:22:04.000 AM 02/28/2013"}}JSON_INFO
Section titled “JSON_INFO”JSON_INFO (vertex_or_edge)Returns the OID, the properties and the label (vertex or edge table name) of the element. For a vertex, adj_list also lists its edges, as JSON_ADJACENCY_LIST does.
SELECT JSON_INFO(m) AS iFROM MATCH (b:brand)-[m:manufactures]->(p:product)WHERE p.id = 1618;{"id":"(0|4931|461)","properties":{"since":"06:22:04.000 AM 02/28/2013"},"label":"manufactures"}The JSON functions combine with it. Diadora has 18 edges: 8 incoming follows edges from customers and 10 outgoing edges, 9 of which are manufactures edges to its products.
SELECT JSON_EXTRACT(JSON_INFO(b), '$.label') AS kind, JSON_EXTRACT(JSON_INFO(b), '$.properties.name') AS brand_name, JSON_LENGTH(JSON_INFO(b), '$.adj_list') AS edgesFROM MATCH (b:brand)WHERE b.name = 'Diadora';| kind | brand_name | edges |
|---|---|---|
| brand | Diadora | 18 |
JSON_GRAPH
Section titled “JSON_GRAPH”JSON_GRAPH (element [, element] ...)Returns the given vertices and edges as one graph document with a nodes array and an edges array. Each edge carries the OIDs of its start and end vertex. Combine it with JSON_PRETTY for readable output.
SELECT JSON_PRETTY(JSON_GRAPH(b, m, p)) AS gFROM MATCH (b:brand)-[m:manufactures]->(p:product)WHERE p.id = 1618;{ "nodes": [ { "id": "(0|4490|63)", "label": "product", "properties": { "id": 1618, "units_in_stock": 22, "unit_price": 29.000000, "description": "Size XL, Black", "name": "Gobi HeatTec Tee" } }, { "id": "(0|4545|52)", "label": "brand", "properties": { "id": 52, "name": "Diadora" } } ], "edges": [ { "id": "(0|4931|461)", "startNodeId": "(0|4545|52)", "endNodeId": "(0|4490|63)", "label": "manufactures", "properties": { "since": "06:22:04.000 AM 02/28/2013" } } ]}JSON_ADJACENCY_LIST
Section titled “JSON_ADJACENCY_LIST”JSON_ADJACENCY_LIST (vertex)Returns all edges of a vertex as a JSON array. Each entry has the OID of the edge (edge_id), the OID of the vertex at the other end (dest) and the direction (dir): "0" for an outgoing edge, "1" for an incoming edge.
SELECT JSON_ADJACENCY_LIST(p) AS adjacency FROM MATCH (p:product) WHERE p.id = 1618;[{"edge_id":"(0|5571|425)","dest":"(0|4609|6)","dir":"0"},{"edge_id":"(0|4677|331)","dest":"(0|4417|23)","dir":"0"},{"edge_id":"(0|4931|461)","dest":"(0|4545|52)","dir":"1"}]The product has two outgoing edges (available_at to a supplier and part_of to a category) and one incoming edge (manufactures from Diadora).
JSON_TOPOLOGY_RECORD
Section titled “JSON_TOPOLOGY_RECORD”JSON_TOPOLOGY_RECORD (vertex)Returns the topology record that the graph engine keeps for a vertex: the vertex OID (prop_oid) and, for each edge, the edge and the adjacent vertex with their labels and visibility.
SELECT JSON_TOPOLOGY_RECORD(p) AS topology FROM MATCH (p:product) WHERE p.id = 1618;{"prop_oid":"(0|4490|63)","list_adj":[{"edge":{"id":"(0|4677|331)","label":"part_of","visible":"yes"},"adj_node":{"id":"(0|4417|23)","label":"category","visible":"yes"}},{"edge":{"id":"(0|4931|461)","label":"manufactures","visible":"yes"},"adj_node":{"id":"(0|4545|52)","label":"brand","visible":"yes"}},{"edge":{"id":"(0|5571|425)","label":"available_at","visible":"yes"},"adj_node":{"id":"(0|4609|6)","label":"supplier","visible":"yes"}}]}JSON_GRAPH_HEAP_MEMORY_USAGE
Section titled “JSON_GRAPH_HEAP_MEMORY_USAGE”JSON_GRAPH_HEAP_MEMORY_USAGE ()Returns statistics about the memory the server uses for the graph topology: the number of vertices and edges, page and container sizes, the size of the in-memory topology and its buffer distribution, and the read-only page buffer. The values depend on the server's state.
SELECT JSON_EXTRACT(JSON_GRAPH_HEAP_MEMORY_USAGE(), '$.vertices.number_of_vertices') AS vertices, JSON_EXTRACT(JSON_GRAPH_HEAP_MEMORY_USAGE(), '$.edges.number_of_edges') AS edges;| vertices | edges |
|---|---|
| 3397 | 12808 |
The top-level members are vertices, edges and ro_page_buffer.