我已经在这个问题上工作了一段时间了。我正在一个统计网站上工作,作为我玩游戏的爱好。
基本上,我有一个脚本,每5分钟访问一次游戏的API(可能将其增加到15分钟),并立即提取所有比赛的当前状态。我最初是将此对象存储为表中的JSON列。(然后,每行的JSON列中都有一个118kb的对象)
问题是试图查询表以获取整个档案的一周时间(这是比赛的持续时间)。基本上,当我想要的只是JSON中的特定密钥时,它将拉长2016个118kb记录,进行为期一周的比赛。对该API端点的请求大约需要10秒钟才能完成!
我仅在PostgreSQL中找到了基于JSON键查询行的方法,但没有找到类似的方法SELECT match.kills FROM matches WHERE...
。
我已经意识到那是行不通的,所以我想尝试从JSON对象中获取键并将其插入到相应的表列中。
JSON对象框架如下所示:
{
id: string,
start_time: timestamp,
end_time: timestamp,
scores: {
green: number,
blue: number,
red: number
},
worlds: number[],
all_worlds: number[][],
deaths: {
green: number,
blue: number,
red: number
},
kills: {
green: number,
blue: number,
red: number
},
maps: [
{
id: number,
type: string,
scores: same as above,
bonuses: {
type: string,
owner: string
},
deaths: same as above,
kills: same as above,
objectives: [
{
id: string,
type: string,
owner: string,
last_flipped: timestamp,
claimed_by: guild id (put this into another api endpoint),
claimed_at: timestamp
},
... (repeat 17 times)
]
},
... (repeat 3 times)
]
}
因此,我想将其作为键存储在数据库中,但是我不确定如何对具有type值的键完成此操作object
。
最终目标是以一种可以通过URL访问的API的方式存储该信息,例如:
mywebsite.com/api/v1/matcharchive?data=kills,deaths,score&matchid=1-1&archive_time=2016-07-09T02:00:00Z
它将只查询数据库中对象中的那三个键并返回它们。
将具有这么多键的JSON对象存储到PSQL表中的正确方法是什么?
您只需要->
在json字段上使用运算符即可。此示例进行了稍微编辑,因此自动增量键略有偏离。
host=# create table tmp1 ( id serial primary key, data json);
CREATE TABLE
host=# \d tmp1
Table "public.tmp1"
Column | Type | Modifiers
--------+---------+---------------------------------------------------
id | integer | not null default nextval('tmp1_id_seq'::regclass)
data | json |
Indexes:
"tmp1_pkey" PRIMARY KEY, btree (id)
host=# insert into tmp1 (data) values ('{"a":1, "b":2}'), ('{"a":3, "b":4}'), ('{"a":5, "c":6}');
INSERT 0 3
host=# select * from tmp1;
id | data
----+----------------
2 | {"a":1, "b":2}
3 | {"a":3, "b":4}
4 | {"a":5, "c":6}
(3 rows)
host=# select id, data->'b' from tmp1;
id | ?column?
----+----------
2 | 2
3 | 4
4 |
(3 rows)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句