Postgres jsonb 'NOT contains' 运算符
Postgres jsonb 'NOT contains' operator
我正在试验 postgres jsonb
列类型,到目前为止一切顺利。
我使用的一个常见查询是这样的:
select count(*) from jsonbtest WHERE attributes @> '{"City":"Mesa"}';
我该如何扭转它?是否有不同的运算符或者它只是用作
select count(*) from jsonbtest WHERE NOT attributes @> '{"City":"Mesa"}';
这可以通过几个条件来实现。
这并不优雅,但我没有找到另一种方法。
因此,首先,获取简单的没有 'City' 属性的每一行,然后添加 'OR' 条件以检查字段值是否正确。
select count(*) from jsonbtest where
NOT(attributes ? 'City')
OR (attributes ? 'City') is NULL -- this is required if attributes can be null
OR (attributes->>'City' != 'Mesa'))
您可以使用运算符 <@
这将搜索 'City' 不是 'Mesa'
的位置
select count(*) from jsonbtest WHERE attributes <@ '{"City":"Mesa"}';
两种方式,您可以测试任何 json(b) 值
->>
运算符将值提取为文本。但是这个操作比较慢,如果你只会使用值test
@>
运算符测试任何 json(b) 包含任何 json(b)。这是一个快速但您未经过测试的 NOT 选项。
简单快捷的方式:
NOT (attribute @> '{"City":"Mesa"}'::jsonb)
我已将 attribute->>'City' <> 'Mesa'
更改为 NOT (attribute @> '{"City":"Mesa"}'::jsonb)
,我的 ~2.000.000 行查询结果时间从 45 秒更改为 25 秒。
---包含特定键(城市)不包含值('"Mesa"')。
SELECT count(*) FROM jsonbtest WHERE not (attributes -> 'City' @> '"Mesa"');
---不包含特定键值对:{"City":"Mesa"}
SELECT count(*) FROM jsonbtest WHERE NOT (attributes @> '{"City":"Mesa"}')
因为属性键可以是 City 以外的其他键。所以这两个查询是不同的!
我正在试验 postgres jsonb
列类型,到目前为止一切顺利。
我使用的一个常见查询是这样的:
select count(*) from jsonbtest WHERE attributes @> '{"City":"Mesa"}';
我该如何扭转它?是否有不同的运算符或者它只是用作
select count(*) from jsonbtest WHERE NOT attributes @> '{"City":"Mesa"}';
这可以通过几个条件来实现。 这并不优雅,但我没有找到另一种方法。
因此,首先,获取简单的没有 'City' 属性的每一行,然后添加 'OR' 条件以检查字段值是否正确。
select count(*) from jsonbtest where
NOT(attributes ? 'City')
OR (attributes ? 'City') is NULL -- this is required if attributes can be null
OR (attributes->>'City' != 'Mesa'))
您可以使用运算符 <@
这将搜索 'City' 不是 'Mesa'
select count(*) from jsonbtest WHERE attributes <@ '{"City":"Mesa"}';
两种方式,您可以测试任何 json(b) 值
->>
运算符将值提取为文本。但是这个操作比较慢,如果你只会使用值test@>
运算符测试任何 json(b) 包含任何 json(b)。这是一个快速但您未经过测试的 NOT 选项。
简单快捷的方式:
NOT (attribute @> '{"City":"Mesa"}'::jsonb)
我已将 attribute->>'City' <> 'Mesa'
更改为 NOT (attribute @> '{"City":"Mesa"}'::jsonb)
,我的 ~2.000.000 行查询结果时间从 45 秒更改为 25 秒。
---包含特定键(城市)不包含值('"Mesa"')。
SELECT count(*) FROM jsonbtest WHERE not (attributes -> 'City' @> '"Mesa"');
---不包含特定键值对:{"City":"Mesa"}
SELECT count(*) FROM jsonbtest WHERE NOT (attributes @> '{"City":"Mesa"}')
因为属性键可以是 City 以外的其他键。所以这两个查询是不同的!