【问题标题】:How to create GIN index on text array column in SQLAlchemy (with PostgreSQL and python)如何在 SQLAlchemy 中的文本数组列上创建 GIN 索引(使用 PostgreSQL 和 python)
【发布时间】:2016-09-20 05:30:09
【问题描述】:

我想在 postgre 表上执行大量查询以按标签过滤

from sqlalchemy.dialects.postgresql import ARRAY

class Post(db.Model):
    __tablename__ = 'post'

    id = db.Column(db.Integer, primary_key=True)
    tags = db.Column(ARRAY(db.String))

This link 建议将标签存储为带有 GIN 索引的文本数组。

如何将 GIN 索引添加到上表?我是否使用 StringText 数据类型也有区别吗?

【问题讨论】:

    标签: python postgresql indexing sqlalchemy flask-sqlalchemy


    【解决方案1】:

    我通过以下方式解决了它:

    from sqlalchemy.dialects.postgresql import ARRAY, array
    
    class Post(db.Model):
        __tablename__ = 'post'
    
        id = db.Column(db.Integer, primary_key=True)
        tags = db.Column(ARRAY(db.Text), nullable=False, default=db.cast(array([], type_=db.Text), ARRAY(db.Text)))
        __table_args__ = (db.Index('ix_post_tags', tags, postgresql_using="gin"), )
    

    并通过简单的查询

    db.session.query(Post).filter(Post.tags.contains([tag]))
    

    必须将数组类型保持为Text 而不是String,否则会发生一些错误

    【讨论】:

    • String 也可以使用强制转换来查询:db.session.query(Post).filter(Post.tags.contains(cast([tag], ARRAY(String)))。需要导入:from sqlalchemy import Stringfrom sqlalchemy.dialects.postgresql import ARRAY
    猜你喜欢
    • 2015-09-02
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-12
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多