Postgres中的JSON查询
我的postgres DB中有一些JSON,它位于一个名为Postgres中的JSON查询,json,postgresql,groovy,Json,Postgresql,Groovy,我的postgres DB中有一些JSON,它位于一个名为site\u content的表中,该表有两行,id和content,在content中存储我的JSON。我希望能够找到一个给定id的玩家,我的玩家存储在键series下,因为这是从JSON创建图表所需的键 以下是我当前使用的查询: Blocking.get { sql.firstRow("""SELECT * from site_content where content -> 'playersCo
site\u content
的表中,该表有两行,id
和content
,在content
中存储我的JSON。我希望能够找到一个给定id的玩家,我的玩家存储在键series
下,因为这是从JSON创建图表所需的键
以下是我当前使用的查询:
Blocking.get {
sql.firstRow("""SELECT * from site_content where content -> 'playersContainer' -> 'series' -> 'id' = ${id} """)
}.map { row ->
log.info("row is: ${row}")
if (row) {
objectMapper.readValue(row.getAt(0).toString(), Player)
}
}
}
但是我得到了这个错误:
org.postgresql.util.PSQLException:错误:运算符不存在:
json=字符变化提示:没有与给定名称匹配的运算符
和参数类型。您可能需要添加显式类型转换
以下是我的JSON示例:
"id": "${ID}",
"team": {
"id": "123",
"name": "Shire Soldiers"
},
"playersContainer": {
"series": [
{
"id": "1",
"name": "Nick",
"teamName": "Shire Soldiers",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
},
{
"id": "2",
"name": "Pasty",
"teamName": "Shire Soldiers",
"ratings": [
6,
8,
9,
10
],
"assists": 25,
"manOfTheMatches": 32,
"cleanSheets": 2,
"data": [
3,
5,
7,
9,
10
],
"totalGoals": 24
}
]
}
我在这个项目中使用Groovy,但我想这只是我遇到的一般JSON postgres语法问题。你说得对,这是SQL语法的问题。更正您的查询:
select * from json_test where content->'playersContainer'->'series' @> '[{"id":"1"}]';
完整示例:
CREATE TABLE json_test (
content jsonb
);
insert into json_test(content) VALUES ('{"id": "1",
"team": {
"id": "123",
"name": "Shire Soldiers"
},
"playersContainer": {
"series": [
{
"id": "1",
"name": "Nick",
"teamName": "Shire Soldiers",
"ratings": [
1,
5,
6,
9
],
"assists": 17,
"manOfTheMatches": 20,
"cleanSheets": 1,
"data": [
3,
2,
3,
5,
6
],
"totalGoals": 19
},
{
"id": "2",
"name": "Pasty",
"teamName": "Shire Soldiers",
"ratings": [
6,
8,
9,
10
],
"assists": 25,
"manOfTheMatches": 32,
"cleanSheets": 2,
"data": [
3,
5,
7,
9,
10
],
"totalGoals": 24
}
]
}}');
select * from json_test where content->'playersContainer'->'series' @> '[{"id":"1"}]';
关于接线员。这可能也很有用。可能有帮助:在sql语句中,我在json字段中添加了这个“cast”:
INSERT INTO map_file(type, data)
VALUES (?, CAST(? AS json))
RETURNING id
map_文件表中“data”的数据类型为:json感谢您的回复,但我收到了以下错误:运算符不存在:json@>未知我正在使用postgres 9.4I将我的内容转换为jsonb,而不是json,它成功了,谢谢!很抱歉,它无法工作,请使用此查询从网站内容中选择内容->'playersContainer'->'series',其中内容->'playersContainer'->'series'@>'[{“id”:“1”}];我用id为1和2的球员回来,我只想1@NickPocock,看来这里的答案可能会有所帮助。在中的第二列中,返回查找的系列元素。它是这样运行的:从json_test t、jsonb_array_元素中选择元素(t.content->'playersContainer'->'series') 作为elem,其中elem->>'id'='1';您只需复制粘贴您的答案?。。。