我正在试验jsonb在Postgres 9.4 中的Postgres 字段中保留以下值:
[{"event_slug":"test_1","start_time":"2014-10-08","end_time":"2014-10-12"},
{"event_slug":"test_2","start_time":"2013-06-24","end_time":"2013-07-02"},
{"event_slug":"test_3","start_time":"2014-03-26","end_time":"2014-03-30"}]
Run Code Online (Sandbox Code Playgroud)
我正在执行以下查询:
SELECT * FROM locations
WHERE EXISTS (
SELECT 1 FROM jsonb_array_elements(events) AS e
WHERE (
e->>'event_slug' = 'test_1' AND
(
e->>'start_time' >= '2014-10-30 14:04:06 -0400' OR
e->>'end_time' >= '2014-10-30 14:04:06 -0400'
)
)
)
Run Code Online (Sandbox Code Playgroud)
如何利用上述查询为该数据创建索引?这对于几百万行来说听起来是否合理?每行包含〜10个事件?
值得注意的是,我似乎仍在进行顺序扫描:
CREATE INDEX events_gin_idx ON some_table USING GIN (events);
Run Code Online (Sandbox Code Playgroud)
我猜是因为我在查询中做的第一件事就是将数据转换为json数组元素.
为了搜索jsonb列中的特定键,我想在该列上创建索引。
使用:Postgres 10.2
忽略一些不相关的列,我有包含animals这些列的表(省略一些不相关的列):
animalid PK number
location (text)
type (text)
name (text)
data (jsonb) for eg: {"age": 2, "tagid": 11 }
Run Code Online (Sandbox Code Playgroud)
我需要根据:location、type和进行搜索tagId。喜欢:
where location = ? and type = 'cat' and (data ->> 'tagid') = ?
Run Code Online (Sandbox Code Playgroud)
其他要点:
如何确保搜索速度快?我考虑过的选项:
animal_id, location, tagId(尽管无法 FK 到分区父表)location在和typejsonb 键上创建索引。tagId- 对于除猫之外的所有动物,该列将为空。我确实在表上的其他列上有一个索引 - 但对如何创建索引以基于快速搜索猫有点困惑tagid。有什么建议么?
更新 …
postgresql indexing database-design postgresql-performance jsonb