19

I want to perform large number of queries to filter by tag, on a postgre table

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 recommends storing tags as text array with a GIN index.

How do I add GIN index to above table? Also does it make a difference whether I use String vs Text datatype?

1 Answer 1

35

I solved it by following:

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"), )

And query simply by

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

Have to keep the array type to Text and not String otherwise some error happens

Sign up to request clarification or add additional context in comments.

1 Comment

String can also be queried by using casting: db.session.query(Post).filter(Post.tags.contains(cast([tag], ARRAY(String))). Imports required: from sqlalchemy import String, from sqlalchemy.dialects.postgresql import ARRAY

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.