Skip to content

Commit ecf1d40

Browse files
table.search_sql(include_rank=True) option (#480)
* search_sql add include_rank option * add test * add FTS4 test * Apply Black Thanks, @chapmanjacobd
1 parent 087753c commit ecf1d40

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

sqlite_utils/db.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2376,6 +2376,7 @@ def search_sql(
23762376
limit: Optional[int] = None,
23772377
offset: Optional[int] = None,
23782378
where: Optional[str] = None,
2379+
include_rank: bool = False,
23792380
) -> str:
23802381
""" "
23812382
Return SQL string that can be used to execute searches against this table.
@@ -2385,6 +2386,7 @@ def search_sql(
23852386
:param limit: SQL limit
23862387
:param offset: SQL offset
23872388
:param where: Extra SQL fragment for the WHERE clause
2389+
:param include_rank: Select the search rank column in the final query
23882390
"""
23892391
# Pick names for table and rank column that don't clash
23902392
original = "original_" if self.name == "original" else "original"
@@ -2427,6 +2429,8 @@ def search_sql(
24272429
rank_implementation = "rank_bm25(matchinfo([{}], 'pcnalx'))".format(
24282430
fts_table
24292431
)
2432+
if include_rank:
2433+
columns_with_prefix_sql += ",\n " + rank_implementation + " rank"
24302434
limit_offset = ""
24312435
if limit is not None:
24322436
limit_offset += " limit {}".format(limit)

tests/test_fts.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,50 @@ def test_enable_fts_error_message_on_views():
556556
" rank_bm25(matchinfo([books_fts], 'pcnalx'))"
557557
),
558558
),
559+
(
560+
{"include_rank": True},
561+
"FTS5",
562+
(
563+
"with original as (\n"
564+
" select\n"
565+
" rowid,\n"
566+
" *\n"
567+
" from [books]\n"
568+
")\n"
569+
"select\n"
570+
" [original].*,\n"
571+
" [books_fts].rank rank\n"
572+
"from\n"
573+
" [original]\n"
574+
" join [books_fts] on [original].rowid = [books_fts].rowid\n"
575+
"where\n"
576+
" [books_fts] match :query\n"
577+
"order by\n"
578+
" [books_fts].rank"
579+
),
580+
),
581+
(
582+
{"include_rank": True},
583+
"FTS4",
584+
(
585+
"with original as (\n"
586+
" select\n"
587+
" rowid,\n"
588+
" *\n"
589+
" from [books]\n"
590+
")\n"
591+
"select\n"
592+
" [original].*,\n"
593+
" rank_bm25(matchinfo([books_fts], 'pcnalx')) rank\n"
594+
"from\n"
595+
" [original]\n"
596+
" join [books_fts] on [original].rowid = [books_fts].rowid\n"
597+
"where\n"
598+
" [books_fts] match :query\n"
599+
"order by\n"
600+
" rank_bm25(matchinfo([books_fts], 'pcnalx'))"
601+
),
602+
),
559603
],
560604
)
561605
def test_search_sql(kwargs, fts, expected):

0 commit comments

Comments
 (0)