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

时间:2019-04-20 08:26:34

标签: python postgresql sqlalchemy jsonb

使用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")

1 个答案:

答案 0 :(得分:1)

提供足够的选择性查询,加快全文本搜索查询的速度,就意味着拥有适当的索引。 jsonb_path_ops不利于全文搜索:

  

非默认GIN运算符类jsonb_path_ops仅支持索引@>运算符。

例如,您需要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))