SQL Alchemy GIN 索引(UUID、JSONB)

SQL Alchemy GIN index on (UUID, JSONB)

我有一个 table 架构,其中有一个 json 字段。该字段已经填充了大量数据。

CREATE TABLE table(
id     UUID      NOT NULL
data    JSON       NOT NULL
);

我想为 json 字段创建索引。我试过下面的脚本

 __table_args__ = (
                  Index("index_table_on_data_gin",
                        "data",
                        postgresql_using='gin',),
               
                  ),
                   Index("index_table_on_id_gin",
                        "id",
                        postgresql_using='gin',),
               
                  ),
                  )

这是我遇到的错误。

JSON 索引创建错误

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject) data type json has no default operator class for access method "gin"

UUID 索引创建错误

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedObject) data type uuid has no default operator class for access method "gin"

您不能索引 json 类型,但您可以索引 jsonb 类型,请参阅 manual. jsonb should be your preferred type (see the manual)

您可以使用 btree_gin 扩展来使用 GIN 索引 UUID(虽然我不明白这一点,为什么不直接使用常规 btree 呢?)