mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
feat(python): expose FTS operators and match counts (#5042)
String full-text searches now accept `operator="AND"` or
`operator="OR"`, preserving the existing OR default. Sync and async FTS
builders expose `count_rows()` to count every match satisfying the
filter, independently of pagination, projection, ordering, and
reranking. Counting streams matching scores without reading document
columns; it can scan all matches.
```python
query = table.search("gripper closed", query_type="fts", operator="AND")
query = query.where("active = true")
matching_rows = query.count_rows()
page = query.limit(20).to_list()
query = await async_table.search("gripper closed", query_type="fts", operator="AND")
matching_rows = await query.where("active = true").count_rows()
```
Phrase searches keep the existing index default and now explain how to
rebuild an index with `FTS(with_position=True)`. AND requests retain
their operator through namespace pushdown and fail explicitly on older
remote servers that cannot represent it. Regression coverage includes
indexed and unindexed queries, filtered counts above the default limit,
pagination preservation, remote serialization, and phrase indexes with
and without positions.
This commit is contained in:
+172
-12
@@ -29,6 +29,7 @@ from lancedb.query import (
|
||||
CombinedFieldsQuery,
|
||||
DocumentGranularity,
|
||||
FullTextOperator,
|
||||
FullTextSearchQuery,
|
||||
MatchQuery,
|
||||
MultiMatchQuery,
|
||||
PhraseQuery,
|
||||
@@ -530,11 +531,9 @@ async def test_fts_select_async(async_table):
|
||||
|
||||
def test_search_fts_phrase_query(table):
|
||||
table.create_fts_index("text", with_position=False)
|
||||
try:
|
||||
phrase_results = table.search('"puppy runs"').limit(100).to_list()
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
table.search('"puppy runs"').limit(100).to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
table.create_fts_index("text", with_position=True, replace=True)
|
||||
results = table.search("puppy").limit(100).to_list()
|
||||
|
||||
@@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table):
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_fts_phrase_query_async(async_table):
|
||||
await async_table.create_index("text", config=FTS(with_position=False))
|
||||
try:
|
||||
phrase_results = (
|
||||
await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
|
||||
)
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
await async_table.query().nearest_to_text('"puppy runs"').to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
await async_table.create_index("text", config=FTS(with_position=True))
|
||||
results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
|
||||
phrase_results = (
|
||||
@@ -1948,3 +1943,168 @@ async def test_async_fts_code_analyzer(mem_db_async):
|
||||
|
||||
rows = await table.query().nearest_to_text("http").to_list()
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected):
|
||||
db = ldb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
table.create_index("text", config=FTS())
|
||||
kwargs = {"fts_columns": "text"}
|
||||
if operator is not None:
|
||||
kwargs["operator"] = operator
|
||||
query = table.search("gripper closed", query_type="fts", **kwargs)
|
||||
assert query.count_rows() == expected
|
||||
assert len(query.limit(100).to_list()) == expected
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", fts_columns="text")
|
||||
.operator("AND")
|
||||
.count_rows()
|
||||
== 15
|
||||
)
|
||||
if operator is not None:
|
||||
assert query.to_query_object().full_text_query.operator == operator
|
||||
query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
assert len(query.to_list()) <= 2
|
||||
assert (
|
||||
table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0
|
||||
)
|
||||
assert (
|
||||
table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows()
|
||||
== 15
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
async def test_simple_fts_operator_and_count_async(
|
||||
tmp_path, indexed, operator, expected
|
||||
):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
await table.create_index("text", config=FTS())
|
||||
query = await table.search(
|
||||
"gripper closed", query_type="fts", fts_columns="text", operator=operator
|
||||
)
|
||||
assert await query.count_rows() == expected
|
||||
assert len(await query.limit(100).to_list()) == expected
|
||||
query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert await query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
direct = table.query().nearest_to_text(
|
||||
"gripper closed", columns="text", operator="AND"
|
||||
)
|
||||
assert await direct.count_rows() == 15
|
||||
assert direct.to_query_object().full_text_query.query.operator == "AND"
|
||||
assert (
|
||||
await table.query().nearest_to_text("absent", columns="text").count_rows() == 0
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
def test_fts_phrase_count_positions(tmp_path, with_position, query):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.search(query, query_type="fts")
|
||||
if with_position:
|
||||
assert search.count_rows() == 1
|
||||
assert len(search.to_list()) == 1
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", operator="AND")
|
||||
.phrase_query()
|
||||
.count_rows()
|
||||
== 1
|
||||
)
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
async def test_fts_phrase_count_positions_async(tmp_path, with_position, query):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
await table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.query().nearest_to_text(query)
|
||||
if with_position:
|
||||
assert await search.count_rows() == 1
|
||||
assert len(await search.to_list()) == 1
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
await search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
def test_fts_operator_rejects_invalid_queries(table):
|
||||
with pytest.raises(ValueError):
|
||||
table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError, match="operator requires a string full-text query"):
|
||||
FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fts_operator_rejects_invalid_queries_async(async_table):
|
||||
with pytest.raises(ValueError):
|
||||
await async_table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
await async_table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError):
|
||||
async_table.query().nearest_to_text(query, operator="AND")
|
||||
|
||||
|
||||
def test_fts_count_fast_search(tmp_path):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"matches", pa.table({"text": ["gripper closed"] * 15})
|
||||
)
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper closed"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").count_rows() == 20
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
|
||||
@@ -18,6 +18,7 @@ import lancedb
|
||||
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
|
||||
from utils import start_server_thread
|
||||
from lancedb.listing import AsyncListing, Listing
|
||||
from lancedb.index import FTS
|
||||
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
|
||||
from lancedb.namespace import (
|
||||
_MAX_QUERY_K,
|
||||
@@ -25,7 +26,7 @@ from lancedb.namespace import (
|
||||
LanceNamespaceDBConnection,
|
||||
_query_to_namespace_request,
|
||||
)
|
||||
from lancedb.query import Query
|
||||
from lancedb.query import FullTextSearchQuery, Query
|
||||
from lancedb.table import AsyncTable, LanceTable
|
||||
|
||||
|
||||
@@ -1524,3 +1525,42 @@ def test_python_namespace_attribute_access(tmp_path):
|
||||
# Missing dunder lookups still raise, so copy/hasattr probes work.
|
||||
assert not hasattr(request, "__missing_dunder__")
|
||||
assert copy.deepcopy(request) == request
|
||||
|
||||
|
||||
@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]])
|
||||
def test_namespace_fts_operator_is_preserved(columns):
|
||||
request = _query_to_namespace_request(
|
||||
["matches"],
|
||||
Query(
|
||||
full_text_query=FullTextSearchQuery(
|
||||
query="gripper closed", columns=columns, operator="AND"
|
||||
)
|
||||
),
|
||||
)
|
||||
structured = request.to_dict()["full_text_query"]["structured_query"]["query"]
|
||||
if columns and len(columns) > 1:
|
||||
assert all(
|
||||
query["operator"] == "And"
|
||||
for query in structured["multi_match"]["match_queries"]
|
||||
)
|
||||
else:
|
||||
assert structured["match"]["operator"] == "And"
|
||||
assert structured["match"].get("column") == (columns[0] if columns else None)
|
||||
|
||||
|
||||
def test_namespace_fts_count_fast_search(tmp_path):
|
||||
properties = {"root": str(tmp_path)}
|
||||
db = lancedb.connect_namespace("dir", properties)
|
||||
table = db.create_table("matches", pa.table({"text": ["gripper"] * 15}))
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
pushed = lancedb.connect_namespace(
|
||||
"dir", properties, namespace_client_pushdown_operations=["QueryTable"]
|
||||
).open_table("matches")
|
||||
assert pushed.search("gripper", query_type="fts").count_rows() == 20
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.use_rte(False).count_rows() == 15
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.count_rows() == 15
|
||||
assert len(query.limit(100).to_list()) == 15
|
||||
|
||||
@@ -7802,3 +7802,46 @@ async def test_remote_index_exist_ok_wire(is_async, background, kwargs):
|
||||
assert body["replace"] is False
|
||||
else:
|
||||
assert "replace" not in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operator", ["AND", "OR"])
|
||||
def test_remote_fts_operator_and_count(operator):
|
||||
def handler(body):
|
||||
query = body["full_text_query"]["query"]["match"]
|
||||
assert query["terms"] == "gripper closed"
|
||||
assert query["operator"] == operator.title()
|
||||
assert query["column"] == "text"
|
||||
assert body["k"] == 2**63 - 1
|
||||
assert "offset" not in body
|
||||
assert body["columns"] == ["_score"]
|
||||
assert body["filter"] == "text IS NOT NULL"
|
||||
assert body["prefilter"] is False
|
||||
return pa.table({"_score": [1.0] * 25})
|
||||
|
||||
with query_test_table(
|
||||
handler, server_version=Version("0.6.0"), vector_columns={}
|
||||
) as table:
|
||||
query = (
|
||||
table.search(
|
||||
"gripper closed",
|
||||
query_type="fts",
|
||||
fts_columns="text",
|
||||
operator=operator,
|
||||
)
|
||||
.where("text IS NOT NULL", prefilter=False)
|
||||
.select(["text"])
|
||||
.limit(1)
|
||||
.offset(3)
|
||||
)
|
||||
assert query.count_rows() == 25
|
||||
assert query.to_query_object().limit == 1
|
||||
assert query.to_query_object().offset == 3
|
||||
|
||||
|
||||
def test_remote_fts_and_rejects_legacy_server():
|
||||
def handler(body):
|
||||
pytest.fail("AND must not silently become OR on a legacy server")
|
||||
|
||||
with query_test_table(handler, vector_columns={}) as table:
|
||||
with pytest.raises(NotImplementedError, match="server version 0.3.0"):
|
||||
table.search("gripper closed", query_type="fts", operator="AND").to_list()
|
||||
|
||||
Reference in New Issue
Block a user