在 PostgreSQL/SQLAlchemy 中加快 JSONB 全文搜索

Speed up JSONB full text search in PostgreSQL/SQLAlchemy

使用 PostgreSQL 和 SQLAlchemy 时,我的 JSONB 全文搜索性能非常慢。我怎样才能加快速度?

型号

class Book(Base):
    __tablename__ = "book"
    id = Column(Integer, primary_key=True)
    jsondata = Column(JSONB)
    __table_args__ = (Index('index_jsondesc',
                      text("(jsondata->'description') jsonb_path_ops"),
                      postgresql_using="gin"),)

在 JSONB 列中进行全文搜索

class BookSearch:
    def __init__(self):
        pass
    def search(keyword):
        self.query = self.query.filter(Book.jsondata['description'].cast(Unicode).match(keyword))

booksearch = BookSearch()
booksearch.search("Python")

如果有足够的选择性查询,加速全文搜索查询意味着有适当的索引。 jsonb_path_ops 不利于全文搜索:

The non-default GIN operator class jsonb_path_ops supports indexing the @> operator only.

相反,您需要(例如)functional index for explicit to_tsvector():

class Book(Base):
    __tablename__ = "book"
    id = Column(Integer, primary_key=True)
    jsondata = Column(JSONB)
    __table_args__ = (
        Index('index_jsondesc',
              func.to_tsvector('english', jsondata['description'].astext),
              postgresql_using="gin"),
    )

请注意,您必须在定义索引时选择要使用的配置。然后,您的查询必须与索引中使用的配置相匹配:

def search(keyword):
    tsvector = func.to_tsvector('english', Book.jsondata['description'].astext)
    self.query = self.query.filter(tsvector.match(keyword))