PostgreSQL jsonb、`?` 和 JDBC [英] PostgreSQL jsonb, `?` and JDBC
问题描述
我使用的是 PostgreSQL 9.4 和很棒的 JSONB 字段类型.我正在尝试查询文档中的字段.以下在 psql CLI 中工作
SELECT id FROM program WHERE document ->部门"?'CS'
当我尝试通过我的 Scala 应用程序运行相同的查询时,我收到以下错误.我正在使用 Play 框架和 Anorm,所以查询看起来像这样
SQL(s"SELECT id FROM program WHERE document -> 'dept' ? {dept}").on('部门 -> "CS")....
<块引用>
SQLException: : 没有为参数 5 指定值.(SimpleParameterList.java:223)
(在我的实际查询中有更多参数)
我可以通过将参数转换为 jsonb
类型并使用 @>
运算符来检查包含情况来解决此问题.
SQL(s"SELECT id FROM program WHERE document -> 'dept' @> {dept}::jsonb").on('部门 -> "CS")....
我不太热衷于周围的工作.我不知道演员是否有性能损失,但它是额外的输入,并且不明显.
还有什么我可以做的吗?
作为避免 ?运算符,您可以创建一个 new operator 做完全相同的操作.
这是原操作符的代码:
创建操作符?(程序 = jsonb_exists,LEFTARG = jsonb,RIGHTARG = 文字,RESTRICT = 控制,JOIN = contjoinsel);SELECT '{"a":1, "b":2}'::jsonb ?'乙';- 真的
使用不同的名称,没有任何冲突,例如#-#并创建一个新名称:
创建操作符#-#(程序 = jsonb_exists,LEFTARG = jsonb,RIGHTARG = 文字,RESTRICT = 控制,JOIN = contjoinsel);SELECT '{"a":1, "b":2}'::jsonb #-# 'b';- 真的
在您的代码中使用这个新的运算符,它应该可以工作.
检查 pgAdmin -> pg_catalog -> Operators 所有使用 ?在名称中.
I am using PostgreSQL 9.4 and the awesome JSONB field type. I am trying to query against a field in a document. The following works in the psql CLI
SELECT id FROM program WHERE document -> 'dept' ? 'CS'
When I try to run the same query via my Scala app, I'm getting the error below. I'm using Play framework and Anorm, so the query looks like this
SQL(s"SELECT id FROM program WHERE document -> 'dept' ? {dept}")
.on('dept -> "CS")
....
SQLException: : No value specified for parameter 5. (SimpleParameterList.java:223)
(in my actual queries there are more parameters)
I can get around this by casting my parameter to type jsonb
and using the @>
operator to check containment.
SQL(s"SELECT id FROM program WHERE document -> 'dept' @> {dept}::jsonb")
.on('dept -> "CS")
....
I'm not too keen on the work around. I don't know if there are performance penalties for the cast, but it's extra typing, and non-obvious.
Is there anything else I can do?
As a workaround to avoid the ? operator, you could create a new operator doing exactly the same.
This is the code of the original operator:
CREATE OPERATOR ?(
PROCEDURE = jsonb_exists,
LEFTARG = jsonb,
RIGHTARG = text,
RESTRICT = contsel,
JOIN = contjoinsel);
SELECT '{"a":1, "b":2}'::jsonb ? 'b'; -- true
Use a different name, without any conflicts, like #-# and create a new one:
CREATE OPERATOR #-#(
PROCEDURE = jsonb_exists,
LEFTARG = jsonb,
RIGHTARG = text,
RESTRICT = contsel,
JOIN = contjoinsel);
SELECT '{"a":1, "b":2}'::jsonb #-# 'b'; -- true
Use this new operator in your code and it should work.
Check pgAdmin -> pg_catalog -> Operators for all the operators that use a ? in the name.
这篇关于PostgreSQL jsonb、`?` 和 JDBC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!