jsquery vs SQL/JSON

SQL/JSON is coming to PostgreSQL 12 and provides a native way to query JSON data (although, to be specific, JSON data stored as a JSONB data type). This also introduces the jsonpath data type which is used for SQL/JSON query expressions. I'll not be going into its usage in detail, or covering performance characteristics (at least not in this post), but I will compare the syntax and functionality with jsquery. Note that this may potentially change prior to final release.

jsquery was introduced as a non-core extension for PostgreSQL 9.4 and higher by Teodor Sigaev, Alexander Korotkov and Oleg Bartunov. Like jsonpath, it also used its own datatype, jsquery.

We have some functions to which we can pass jsonpath expressions to, 2 of which have operators which can be used as shorthand (albeit without additional parameter control, as they exist primarily for indexing purposes):

These will suppress errors where there's a lack of an array element, object field, an unexpected JSON type or numeric errors.

Here are some examples of how jsquery and SQL/JSON differ in practice. (Note that jsquery usage requires installation of the jsquery extension):

We will select all elements from an array which are equal to 1. Note that, here, jsquery returns an array containing 1, whereas jsonpath returns a scalar value of 1.

jsquery

jsonpath

Now we'll check that all elements are greater than 1 and less than 5.

jsquery

jsonpath

And here we have some jsonb data as follows:

We want books by William Shakespeare.

jsquery

jsonpath

You can see that, while they share some characteristics, they are not the same. It's also possible to control whether it uses lax or strict rules which determine whether or not to throw an error if referencing a non-existing object member or a structural issue. "lax" suppresses such errors, "strict" doesn't. These are placed at the beginning of the jsonpath expression.

So we end up with the following syntax for jsonpath:

I've put together some comparisons between jsquery and jsonpath expressions.

Note that, unlike SQL expressions, you can use the equality operator with "null", whereas you would usually have to state IS NULL. This is because it's not directly equivalent.

jsquery features not present in SQL/JSON.

jsquery supports index hints, but this was necessary as the optimiser has no knowledge of the contents of jsquery strings or statistics related to individual values. So this feature is effectively redundant when it comes to SQL/JSON.

Limitations

Only text, numeric and boolean types are supported at present. Datetime is still a work in progress, so these are intended to be supported in JSONB in future.

For more information on the jsonpath and SQL/JSON, see the PostgreSQL documentation:

SQL/JSON Path Expressionsjsonpath Type

添加评论
点赞收藏
点踩分享查看原文
评论
?
参与讨论