我需要使用 SQLAlchemy 在 Python 中创建一个 PostgreSQL 全文搜索索引。这是我想要的 SQL:
CREATE TABLE person ( id INTEGER PRIMARY KEY, name TEXT );
CREATE INDEX person_idx ON person USING GIN (to_tsvector('simple', name));
现在如何在使用 ORM 时使用 SQLAlchemy 执行第二部分:
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
最佳答案
您可以在 __table_args__
中使用 Index
创建索引。此外,如果需要多个字段,我还使用一个函数来创建 ts_vector
以使其更加整洁和可重用。如下所示:
from sqlalchemy.dialects import postgresql
def create_tsvector(*args):
exp = args[0]
for e in args[1:]:
exp += ' ' + e
return func.to_tsvector('english', exp)
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
__ts_vector__ = create_tsvector(
cast(func.coalesce(name, ''), postgresql.TEXT)
)
__table_args__ = (
Index(
'idx_person_fts',
__ts_vector__,
postgresql_using='gin'
)
)
更新: 使用索引的示例查询(根据评论更正):
people = Person.query.filter(Person.__ts_vector__.match(expressions, postgresql_regconfig='english')).all()
关于python - 在 PostgreSQL 上使用 SQLAlchemy 创建全文搜索索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42388956/