在 PostgreSQL 中使用布尔值索引所有 JSONB 字段的最佳方法
Best Way to Index All JSONB Fields With Boolean Values in PostgreSQL
我正在创建一个具有 features
jsonb 列的 table。将有一组动态的特征(每行可以有一组未知的特征)。每个特征都是布尔 true/false 值。
示例:
- 第 1 行:特征:{ "happy":正确,"tall":错误,"motivated":正确}
- 第 2 行:特征:{ "happy":正确,"fast":正确,"strong":错误}
- 第 3 行:特征:{ "smart":正确,"fast":正确,"sleepy":错误}
索引此列的最佳方法是什么,以便我可以进行查询以查找所有 featureX = true 的行?我查找的所有示例似乎都需要一个字段名称作为索引的基础。
您可以在完整的 JSON 值上创建索引:
create index on the_table using gin (features);
它可以用于例如@>
运算符:
select *
from the_table
where features @> '{"happy": true}'
另一种方法是不存储 key/value 对,而只列出数组中 "true" 的特征:["happy", "motivated"]
然后使用 ?
运算符.这样 JSON 值会小一点,这样可能会更有效率。
select *
from the_table
where features ? 'happy'
或者如果您想测试多项功能:
select *
from the_table
where features ?| array['happy', 'motivated']
那也可以利用GIN索引
我正在创建一个具有 features
jsonb 列的 table。将有一组动态的特征(每行可以有一组未知的特征)。每个特征都是布尔 true/false 值。
示例:
- 第 1 行:特征:{ "happy":正确,"tall":错误,"motivated":正确}
- 第 2 行:特征:{ "happy":正确,"fast":正确,"strong":错误}
- 第 3 行:特征:{ "smart":正确,"fast":正确,"sleepy":错误}
索引此列的最佳方法是什么,以便我可以进行查询以查找所有 featureX = true 的行?我查找的所有示例似乎都需要一个字段名称作为索引的基础。
您可以在完整的 JSON 值上创建索引:
create index on the_table using gin (features);
它可以用于例如@>
运算符:
select *
from the_table
where features @> '{"happy": true}'
另一种方法是不存储 key/value 对,而只列出数组中 "true" 的特征:["happy", "motivated"]
然后使用 ?
运算符.这样 JSON 值会小一点,这样可能会更有效率。
select *
from the_table
where features ? 'happy'
或者如果您想测试多项功能:
select *
from the_table
where features ?| array['happy', 'motivated']
那也可以利用GIN索引