我目前正在使用postgres(版本9.4.4)将项目的整个json文档保存在一个表中(简化):
CREATE TABLE projects (
id numeric(19,0) NOT NULL,
project bson NOT NULL )
项目json是这样的(OVERLY-simplified):
{
"projectData": {
"guid":"project_guid",
"name":"project_name"
},
"types": [
{
"class":"window",
"provider":"glassland"
"elements":[
{
"name":"example_name",
"location":"2nd floor",
"guid":"1a",
},
{
"name":"example_name",
"location":"3rd floor",
"guid":"2a",
}
]
},
{
"class":"door",
"provider":"woodland"
"elements":[
{
"name":"example_name",
"location":"1st floor",
"guid":"3a",
},
{
"name":"example_name",
"location":"2nd floor",
"guid":"4a",
}
]
}
]
}
我一直在阅读有关运营商的文档 - >, - >>,#>,@>等等。我做了一些测试和成功选择。但我无法正确编制索引,特别是嵌套数组(类型和元素)。
这些是一些示例选择我想学习如何优化(有很多这样的):
select distinct types->'class' as class, types->'provider' as type
from projects, jsonb_array_elements(project#>'{types}') types;
select types->>'class' as class,
types->>'provider' as provider,
elems->>'name' as name,
elems->>'location' as location,
elems->>'guid' as guid,
from projects, jsonb_array_elements(project#>'{types}') types, jsonb_array_elements(types#>'{elements}') elems
where types->>'class' like 'some_text%' and elems->'guid' <> '""';
我也有这个索引:
CREATE INDEX idx_gin ON projects USING GIN (project jsonb_ops);
这两个选择都有效,但他们不使用te @&gt;运算符或任何可以使用GIN索引的运算符。我无法使用btree((obra-&gt;&gt;'types'));)创建索引btree(在tcq.json_test上创建索引idx_btree,因为值的大小超出限制(对于真正的json)。另外,我不能(或者我不知道如何)创建一个索引,比方说,元素的指针(使用btree在tcq.json_test上创建索引idx_btree2((obra-&gt;&gt;'types') - &gt;&gt;'elements' - &gt;&gt;'guid')); )。这会产生语法错误。
我一直试图使用@&gt;将查询翻译成某些内容但事情是这样的:
select count(*)
from projects, jsonb_array_elements(project#>'{types}') types
where types->>'class' = 'window';
select count(*)
from projects
where obra @> '{"types":[{"class":"window"}]}';
产生不同的输出。
有没有办法正确索引该json的嵌套数组?或者正确选择利用GIN指数?