在PostgreSQL上使用SQLAlchemy创建全文搜索索引

Mar*_*nen 7 python postgresql sqlalchemy python-3.x flask-sqlalchemy

我需要使用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));
Run Code Online (Sandbox Code Playgroud)

现在,在使用ORM时,如何使用SQLAlchemy执行第二部分:

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
Run Code Online (Sandbox Code Playgroud)

ben*_*nvc 15

@sharez的答案非常有用(尤其是当您需要连接索引中的列时)。对于希望在单列上创建 tsvector GIN 索引的任何人,您可以使用以下内容简化原始答案方法:

from sqlalchemy import Column, Index, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func


Base = declarative_base()

class Example(Base):
    __tablename__ = 'examples'

    id = Column(Integer, primary_key=True)
    textsearch = Column(String)

    __table_args__ = (
        Index(
            'ix_examples_tsv',
            func.to_tsvector('english', textsearch),
            postgresql_using='gin'
            ),
        )
Run Code Online (Sandbox Code Playgroud)

请注意,Index(...)in后面的逗号__table_args__不是样式选择,其值__table_args__必须是元组、字典或None

如果您确实需要在多列上创建 tsvector GIN 索引,这是使用text().

from sqlalchemy import Column, Index, Integer, String, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import func


Base = declarative_base()

def to_tsvector_ix(*columns):
    s = " || ' ' || ".join(columns)
    return func.to_tsvector('english', text(s))

class Example(Base):
    __tablename__ = 'examples'

    id = Column(Integer, primary_key=True)
    atext = Column(String)
    btext = Column(String)

    __table_args__ = (
        Index(
            'ix_examples_tsv',
            to_tsvector_ix('atext', 'btext'),
            postgresql_using='gin'
            ),
        )
Run Code Online (Sandbox Code Playgroud)


sha*_*rez 10

您可以使用Indexin 创建索引__table_args__.此外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'
        )
    )
Run Code Online (Sandbox Code Playgroud)

更新: 使用索引的示例查询:

query = Person.__ts_vector__.match(expressions, postgresql_regconfig='english')
people = query.all()
Run Code Online (Sandbox Code Playgroud)

  • @apaleja `match` 是一个运算符,因此它应该在 `filter` 方法中,如下所示: ```Person.query.filter(Person.__ts_vector__.match(expressions, postgresql_regconfig='english')).all( )```` (2认同)

小智 8

@sharez 和 @benvc 已经回答了。不过,我需要让它与重量一起工作。这就是我根据他们的回答做到的:

from sqlalchemy import Column, func, Index, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.operators import op

CONFIG = 'english'

Base = declarative_base()

def create_tsvector(*args):
    field, weight = args[0]
    exp = func.setweight(func.to_tsvector(CONFIG, field), weight)
    for field, weight in args[1:]:
        exp = op(exp, '||', func.setweight(func.to_tsvector(CONFIG, field), weight))
    return exp

class Example(Base):
    __tablename__ = 'example'

    foo = Column(String)
    bar = Column(String)

    __ts_vector__ = create_tsvector(
        (foo, 'A'),
        (bar, 'B')
    )

    __table_args__ = (
        Index('my_index', __ts_vector__, postgresql_using='gin'),
    )
Run Code Online (Sandbox Code Playgroud)


Jin*_*ing 8

感谢这个问题和答案。

我想用蒸馏器来管理使用的版本添加更多一点的情况下,PPL自动生成 其创建索引似乎没有被检测到。

我们可能最终会编写自己的更改脚本,看起来像。

"""add fts idx

Revision ID: e3ce1ce23d7a
Revises: 079c4455d54d
Create Date: 

"""

# revision identifiers, used by Alembic.
revision = 'e3ce1ce23d7a'
down_revision = '079c4455d54d'

from alembic import op
import sqlalchemy as sa


def upgrade():
    op.create_index('idx_content_fts', 'table_name',
            [sa.text("to_tsvector('english', content)")],
            postgresql_using='gin')


def downgrade():
    op.drop_index('idx_content_fts')
Run Code Online (Sandbox Code Playgroud)