繁体   English   中英

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

[英]Create a Full Text Search index with SQLAlchemy on PostgreSQL

我需要使用 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)

您可以使用Index in __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'
        )
    )

更新:使用索引的示例查询(根据评论更正):

people = Person.query.filter(Person.__ts_vector__.match(expressions, postgresql_regconfig='english')).all()

@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'
            ),
        )

请注意, __table_args__Index(...)后面的逗号不是样式选择, __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'
            ),
        )

感谢这个问题和答案。

我想添加更多内容,以防人们使用 alembic 通过使用自动生成来管理版本,这似乎无法检测到创建索引。

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

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

@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'),
    )

这里以前的答案有助于指出正确的方向。 下面是使用 ORM 方法和来自TSVectorType sqlalchemy-utils TSVectorType 帮助程序的提炼和简化方法(这是非常基本的,如果需要可以简单地复制/粘贴以避免外部依赖性https://sqlalchemy-utils.readthedocs.io/en/latest /_modules/sqlalchemy_utils/types/ts_vector.html ):

在从源文本字段自动填充的 ORM 模型(声明性)中定义TSVECTOR列 ( TSVectorType )

import sqlalchemy as sa
from sqlalchemy_utils.types.ts_vector import TSVectorType
# ^-- https://sqlalchemy-utils.readthedocs.io/en/latest/_modules/sqlalchemy_utils/types/ts_vector.html


class MyModel(Base):
    __tablename__ = 'mymodel'
    id = sa.Column(sa.Integer, primary_key=True)
    content = sa.Column(sa.String, nullable=False)

    content_tsv = sa.Column(
        TSVectorType("content", regconfig="english"),
        sa.Computed("to_tsvector('english', \"content\")", persisted=True))
    #      ^-- equivalent for SQL:
    #   COLUMN content_tsv TSVECTOR GENERATED ALWAYS AS (to_tsvector('english', "content")) STORED;

    __table_args__ = (
        # Indexing the TSVector column
        sa.Index("idx_mymodel_content_tsv", content_tsv, postgresql_using="gin"), 
    )

有关使用 ORM 进行查询的更多详细信息,请参阅https://stackoverflow.com/a/73999486/11750716(SQLAlchemy SQLAlchemy 1.4SQLAlchemy 2.0之间存在重要区别)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM