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")
解决方案
给定足够的选择性查询,加快全文搜索查询意味着有适当的索引。jsonb_path_ops
不利于全文搜索:
非默认 GIN 运算符类仅
jsonb_path_ops
支持对运算符进行索引@>
。
相反,您需要(例如)显式的功能索引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))
推荐阅读
- splunk-query - 在 splunk 中搜索唯一 IP
- docker - Kubernetes:将 pod STDOUT、STDERR 和 pod 终止日志重定向到 PVC 文件
- java - 动态(以编程方式)创建视图时,视图在卡片视图中重叠
- spring-boot - 无法从 spring 控制器打印 JSP,但结果是在控制台中打印
- java - 上下文:组件扫描在 junit 中不起作用
- php - 如何使用codeigniter同时创建多个excel文件
- javascript - 创建矩形后如何动态附加文本
- sql - 计算一列中的行但在不同的日期
- angular - 是否可以将 amazon cognito 与 Kinesis 数据流一起使用,充当生产者(生产者是 Angular 应用程序)?
- .net - 过滤器的正则表达式