[英]Speed up JSONB full text search in PostgreSQL/SQLAlchemy
The performance of my JSONB full text search is awfully slow using PostgreSQL and SQLAlchemy. 使用PostgreSQL和SQLAlchemy,我的JSONB全文搜索的性能非常慢。 How can I speed it up? 我如何加快速度?
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"),)
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")
Given selective enough queries, speeding up full text search queries means having the proper index in place. 给定足够的选择性查询,加快全文搜索查询的速度就意味着要有适当的索引。 jsonb_path_ops
do not benefit full text search: jsonb_path_ops
不利于全文搜索:
The non-default GIN operator class
jsonb_path_ops
supports indexing the@>
operator only. 非默认GIN运算符类jsonb_path_ops
支持对@>
运算符进行索引。
Instead you need (for example) a functional index for explicit to_tsvector()
: 相反,您需要(例如) 显式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"),
)
Note that you must choose the configuration to use when defining the index. 请注意,在定义索引时,必须选择要使用的配置。 Your query must then match the configuration used in the index: 然后,您的查询必须与索引中使用的配置匹配:
def search(keyword):
tsvector = func.to_tsvector('english', Book.jsondata['description'].astext)
self.query = self.query.filter(tsvector.match(keyword))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.