[英]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"),)
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.