Postgres 中 JSON 和 JSONB 的区别

Difference between JSON and JSONB in Postgres

PosgresSQL 中 JSON 和 JSONB 数据类型有什么区别?

  1. 具体什么时候用?
  2. 相对于其他有什么好处或坏处?

这是解释: https://www.citusdata.com/blog/2016/07/14/choosing-nosql-hstore-json-jsonb/

In most cases JSONB is likely what you want when looking for a NoSQL, schema-less, datatype. Hstore and JSON can have their place as well but it’s less common. More broadly, JSONB isn’t always a fit in every data model. Where you can normalize there are benefits, but if you do have a schema that has a large number of optional columns (such as with event data) or the schema differs based on tenant id then JSONB can be a great fit. In general you want:

JSONB - In most cases
JSON - If you’re just processing logs, don’t often need to query, and use as more of an audit trail
hstore - Can work fine for text based key-value looks, but in general JSONB can still work great here

json 基本上是一个以原始格式存储 JSON 数据的 blob,甚至保留一些无关紧要的东西,例如空格、对象中键的顺序,甚至是对象中的重复键。它确实提供了执行一些基本 JSON 操作的能力,例如提取与对象中某个键关联的值,尽管这样做速度很慢,因为它每次都必须解析 JSON blob。它还验证每个值以检查它是否有效 JSON。另一方面,jsonb 以自定义格式存储 JSON 数据,该格式针对某些操作进行了优化,例如提取与对象中某个键关联的值(即它不会重新解析 JSON,它不会线性搜索)。此外,jsonb 支持更多操作,例如对象的串联或在对象内部设置值。

一般来说,我只在知道我不会做任何JSON操作或只是偶尔做的情况下才使用json。对于所有其他情况,我使用 jsonb。请注意,对于前一种情况,text 也是一个完全有效的选项,特别是如果您对 json 所做的验证不感兴趣(例如,因为您信任数据源)。