SQLite FTS 5 允许匹配整个索引:
SELECT product_name, description, retail_price
FROM auctionlot_idx
WHERE auctionlot_idx MATCH 'mx AND master AND dongel'
这将匹配 FTS 索引中包含 mx & master 和 dongel 的文档。我正在尝试将此功能与 SQLAlchemy 集成,遵循这个出色的答案作为指南。在答案接近尾声时,它演示了如何使用 MATCH 运算符:
stmt = select(AuctionLotIdx).where(AuctionLotIdx.product_name.op("MATCH")("mx master"))
我想知道生成像上面这样的查询的最佳方法是什么,同时尽可能保持 SQLAlchemy 的做事方式。
以下是我认为可能的解决方法,但并不等同,例如其中一个术语可能只出现在一列中:
SELECT product_name, description, retail_price
FROM auctionlot_idx
WHERE auctionlot_idx.product_name MATCH 'mx AND master AND dongel'
OR auctionlot_idx.description MATCH 'mx AND master AND dongel'
OR auctionlot_idx.title MATCH 'mx AND master AND dongel'
由于没有任何列本身与整个条件匹配,因此此查询将不起作用。
正如@python_user 和我链接的答案的评论中所指出的,执行此操作的方法是使用 column
以及我使用它的方式如下:
def fts_column_MATCH(table: Table) -> Callable[[Any], BinaryExpression[Any]]:
return column(table.__tablename__).op("MATCH")
# later
stmt = select(AuctionLotIdx).where(fts_column_MATCH(AuctionLotIdx)("some FTS query"))
也许有一种更 SQLAlchem-ic 的方式来编写它以使其更符合风格,但这对我有用。