table.search_sql(include_rank=True) option (#480)

* search_sql add include_rank option
* add test
* add FTS4 test
* Apply Black

Thanks, @chapmanjacobd
This commit is contained in:
Jacob Chapman 2022-08-30 22:40:35 -05:00 committed by GitHub
commit ecf1d40112
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 48 additions and 0 deletions

View file

@ -2376,6 +2376,7 @@ class Table(Queryable):
limit: Optional[int] = None, limit: Optional[int] = None,
offset: Optional[int] = None, offset: Optional[int] = None,
where: Optional[str] = None, where: Optional[str] = None,
include_rank: bool = False,
) -> str: ) -> str:
""" " """ "
Return SQL string that can be used to execute searches against this table. Return SQL string that can be used to execute searches against this table.
@ -2385,6 +2386,7 @@ class Table(Queryable):
:param limit: SQL limit :param limit: SQL limit
:param offset: SQL offset :param offset: SQL offset
:param where: Extra SQL fragment for the WHERE clause :param where: Extra SQL fragment for the WHERE clause
:param include_rank: Select the search rank column in the final query
""" """
# Pick names for table and rank column that don't clash # Pick names for table and rank column that don't clash
original = "original_" if self.name == "original" else "original" original = "original_" if self.name == "original" else "original"
@ -2427,6 +2429,8 @@ class Table(Queryable):
rank_implementation = "rank_bm25(matchinfo([{}], 'pcnalx'))".format( rank_implementation = "rank_bm25(matchinfo([{}], 'pcnalx'))".format(
fts_table fts_table
) )
if include_rank:
columns_with_prefix_sql += ",\n " + rank_implementation + " rank"
limit_offset = "" limit_offset = ""
if limit is not None: if limit is not None:
limit_offset += " limit {}".format(limit) limit_offset += " limit {}".format(limit)

View file

@ -556,6 +556,50 @@ def test_enable_fts_error_message_on_views():
" rank_bm25(matchinfo([books_fts], 'pcnalx'))" " rank_bm25(matchinfo([books_fts], 'pcnalx'))"
), ),
), ),
(
{"include_rank": True},
"FTS5",
(
"with original as (\n"
" select\n"
" rowid,\n"
" *\n"
" from [books]\n"
")\n"
"select\n"
" [original].*,\n"
" [books_fts].rank rank\n"
"from\n"
" [original]\n"
" join [books_fts] on [original].rowid = [books_fts].rowid\n"
"where\n"
" [books_fts] match :query\n"
"order by\n"
" [books_fts].rank"
),
),
(
{"include_rank": True},
"FTS4",
(
"with original as (\n"
" select\n"
" rowid,\n"
" *\n"
" from [books]\n"
")\n"
"select\n"
" [original].*,\n"
" rank_bm25(matchinfo([books_fts], 'pcnalx')) rank\n"
"from\n"
" [original]\n"
" join [books_fts] on [original].rowid = [books_fts].rowid\n"
"where\n"
" [books_fts] match :query\n"
"order by\n"
" rank_bm25(matchinfo([books_fts], 'pcnalx'))"
),
),
], ],
) )
def test_search_sql(kwargs, fts, expected): def test_search_sql(kwargs, fts, expected):