💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Include offset rows in similar() candidates (#1291)
Yash Raj Pandey6a15ed849012
diff --git a/docs/embeddings/query.md b/docs/embeddings/query.mdindex 6b5e2caa..55b2274f 100644--- a/docs/embeddings/query.md+++ b/docs/embeddings/query.md@@ -54,6 +54,8 @@ The number of candidates should be larger than the desired number of results whe- For a single query filter clause, the default is the query limit- With multiple filtering clauses, the default is 10x the query limit+When a query orders results by score, its `offset` adds to the query limit.+The index name is only applicable when [subindexes](../configuration/general/#indexes) are enabled. This specifies the index to use for the query.Weights sets the hybrid score weights when an index has both a sparse and dense index.diff --git a/src/python/txtai/database/sql/base.py b/src/python/txtai/database/sql/base.pyindex 5c36f08c..70186539 100644--- a/src/python/txtai/database/sql/base.py+++ b/src/python/txtai/database/sql/base.py@@ -66,6 +66,10 @@ class SQL:if similar:clauses["similar"] = similar+ # Add select column aliases, if any. Only a query with an offset uses them.+ if aliases and clauses["offset"]:+ clauses["aliases"] = aliases+# Return clauses, default to full query if this is not a SQL queryreturn clauses if clauses else {"similar": [[query]]}diff --git a/src/python/txtai/embeddings/search/base.py b/src/python/txtai/embeddings/search/base.pyindex c126767d..c85be551 100644--- a/src/python/txtai/embeddings/search/base.py+++ b/src/python/txtai/embeddings/search/base.py@@ -228,8 +228,8 @@ class Search:# Override limit with query limit, if applicablelimit = max(limit, self.limit(queries))- # Bulk index scan- scan = Scan(self.search, limit, weights, index)(queries, parameters)+ # Bulk index scan. The database query skips OFFSET rows, so add them to the number of candidates.+ scan = Scan(self.search, limit + self.offset(queries), weights, index)(queries, parameters)# Combine index search results with database search resultsresults = []@@ -296,6 +296,32 @@ class Search:return qlimit+ def offset(self, queries):+ """+ Parses the largest OFFSET clause from queries ordered by score.++ Args:+ queries: list of queries++ Returns:+ largest offset number or 0 if not found+ """++ qoffset = 0+ for query in queries:+ # Skip non-numeric offsets (e.g. a ":n" bind parameter)+ o = query.get("offset")+ o = int(o) if o and o.isdigit() else 0++ # Only a query ordered first by score desc counts its offset. Any other order, or a select alias named score that replaces+ # the similarity score in the order, must see the same candidates on every page.+ if o > qoffset:+ orderby = query.get("orderby")+ if (not orderby or orderby.split(",")[0].strip().lower() == "score desc") and "score" not in query.get("aliases", {}):+ qoffset = o++ return qoffset+def graphsearch(self, queries, limit, weights, index):"""Executes an index + graph search.@@ -316,8 +342,8 @@ class Search:# Override limit with query limit, if applicablelimit = max(limit, self.limit(queries))- # Bulk index scan- scan = Scan(self.search, limit, weights, index)(queries, None)+ # Bulk index scan. The graph query drops SKIP rows, so add them to the number of candidates.+ scan = Scan(self.search, limit + self.offset(queries), weights, index)(queries, None)# Combine index search results with database search resultsfor x, query in enumerate(queries):diff --git a/src/python/txtai/graph/query.py b/src/python/txtai/graph/query.pyindex 219f07b4..baf08918 100644--- a/src/python/txtai/graph/query.py+++ b/src/python/txtai/graph/query.py@@ -88,7 +88,7 @@ class Query:"""# Parameters- where, limit, nodes, similar = None, None, [], []+ where, limit, offset, nodes, similar = None, None, None, [], []# Parse where clausematch = re.search(r"where(.+?)return", query, flags=re.DOTALL | re.IGNORECASE)@@ -100,6 +100,13 @@ class Query:if match:limit = match.group(1)+ # Parse skip clause when results are ordered first by score desc. Graph results with no ORDER BY do not follow score order.+ # Most queries have no SKIP, so check for the keyword before the regex.+ if "skip" in query.lower():+ match = re.search(r"skip\s+(\d+)", query, flags=re.DOTALL | re.IGNORECASE)+ if match and re.search(r"order\s+by\s+\w+\.score\s+desc", query, flags=re.DOTALL | re.IGNORECASE):+ offset = match.group(1)+# Parse similar clausesfor x, match in enumerate(re.finditer(r"similar\((.+?)\)", query, flags=re.DOTALL | re.IGNORECASE)):# Replace similar clause with placeholder@@ -115,6 +122,7 @@ class Query:"query": query,"where": where,"limit": limit,+ "offset": offset,"nodes": nodes,"similar": similar,}diff --git a/test/python/testembeddings.py b/test/python/testembeddings.pyindex 0092c96b..582ebaaf 100644--- a/test/python/testembeddings.py+++ b/test/python/testembeddings.py@@ -450,6 +450,64 @@ class TestEmbeddings(unittest.TestCase):# A plain integer limit still worksself.assertEqual(len(embeddings.search("select id from txtai order by id limit 3")), 3)+ def testOffset(self):+ """+ Test an OFFSET clause with a similar clause+ """++ # Longer documents score lower, which sorts the results by id+ embeddings = Embeddings({"keyword": True, "content": True})+ embeddings.index([(uid, "apple " + "pie " * uid, None) for uid in range(10)])++ # First page+ results = embeddings.search("select id from txtai where similar('apple') limit 3")+ self.assertEqual([x["id"] for x in results], ["0", "1", "2"])++ # Second page must not be empty+ results = embeddings.search("select id from txtai where similar('apple') limit 3 offset 3")+ self.assertEqual([x["id"] for x in results], ["3", "4", "5"])++ # An explicit ORDER BY score DESC pages the same way+ results = embeddings.search("select id from txtai where similar('apple') ORDER BY score DESC limit 3 offset 3")+ self.assertEqual([x["id"] for x in results], ["3", "4", "5"])++ # Selecting the score column pages the same way+ results = embeddings.search("select id, score from txtai where similar('apple') limit 3 offset 3")+ self.assertEqual([x["id"] for x in results], ["3", "4", "5"])++ # A tie-breaker after score DESC pages the same way+ results = embeddings.search("select id from txtai where similar('apple') order by score desc, id limit 3 offset 3")+ self.assertEqual([x["id"] for x in results], ["3", "4", "5"])++ # A bind parameter offset is not a number, so it does not add candidates+ results = embeddings.search("select id from txtai where similar('apple') limit 3 offset :n", parameters={"n": 0})+ self.assertEqual([x["id"] for x in results], ["0", "1", "2"])++ # Each query in a batch gets its own page+ queries = [f"select id from txtai where similar('apple') limit 3{offset}" for offset in [" offset 3", " offset 6", ""]]+ results = embeddings.batchsearch(queries)+ self.assertEqual([[x["id"] for x in result] for result in results], [["3", "4", "5"], ["6", "7", "8"], ["0", "1", "2"]])++ def testOffsetOrderBy(self):+ """+ Test an OFFSET clause with a similar clause and an ORDER BY other than score DESC+ """++ embeddings = Embeddings({"keyword": True, "content": True})+ embeddings.index([(uid, {"text": "apple " + "pie " * uid, "n": uid}, None) for uid in range(40)])++ # Every page sorts the same 30 candidates, the default of 10x the query limit+ for orderby in ["n desc", "n desc, score desc", "score asc"]:+ query = f"select n from txtai where similar('apple') and n >= 0 order by {orderby} limit 3"+ self.assertEqual([x["n"] for x in embeddings.search(query)], [29, 28, 27])+ self.assertEqual([x["n"] for x in embeddings.search(f"{query} offset 3")], [26, 25, 24])++ # A select alias named score replaces the similarity score in the order+ for select, orderby in [("n as score", " order by score desc"), ("n as score", ""), ("n score", ""), ('n as "score"', "")]:+ query = f"select {select} from txtai where similar('apple') and n >= 0{orderby} limit 3"+ self.assertEqual([x["score"] for x in embeddings.search(query)], [29, 28, 27])+ self.assertEqual([x["score"] for x in embeddings.search(f"{query} offset 3")], [26, 25, 24])+def testQuantize(self):"""Test scalar quantizationdiff --git a/test/python/testgraph.py b/test/python/testgraph.pyindex b43afe3a..2893dd47 100644--- a/test/python/testgraph.py+++ b/test/python/testgraph.py@@ -539,6 +539,32 @@ class TestGraph(unittest.TestCase):)self.assertEqual(len(results[0]), 3)+ def testSearchSkip(self):+ """+ Test a SKIP clause with a similar clause+ """++ # Longer documents score lower, which sorts the results by id+ embeddings = Embeddings({"keyword": True, "content": True, "graph": True})+ embeddings.index([(uid, "apple " + "pie " * uid, None) for uid in range(40)])++ # SKIP 30 is past the default of 10x the query limit as candidates+ results = embeddings.search("MATCH (A) WHERE SIMILAR(A, 'apple') RETURN A.id ORDER BY A.score DESC SKIP 30 LIMIT 3")+ self.assertEqual([x["A.id"] for x in results], [30, 31, 32])++ # A tie-breaker after A.score DESC pages the same way+ results = embeddings.search("MATCH (A) WHERE SIMILAR(A, 'apple') RETURN A.id ORDER BY A.score DESC, A.id SKIP 30 LIMIT 3")+ self.assertEqual([x["A.id"] for x in results], [30, 31, 32])++ # Keywords are not case sensitive+ results = embeddings.search("MATCH (A) WHERE SIMILAR(A, 'apple') RETURN A.id Order By A.score Desc Skip 30 Limit 3")+ self.assertEqual([x["A.id"] for x in results], [30, 31, 32])++ # Any other ORDER BY sorts the same 30 candidates on every page+ for orderby in ["A.id DESC", "A.id DESC, A.score DESC", "A.score"]:+ results = embeddings.search(f"MATCH (A) WHERE SIMILAR(A, 'apple') RETURN A.id ORDER BY {orderby} SKIP 3 LIMIT 3")+ self.assertEqual([x["A.id"] for x in results], [26, 25, 24])+def testSimple(self):"""Test creating a simple graph