Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Match whole similar placeholders in SQL and graph queries (#1512)

Fahmid Arman722df40ae80b
diff --git a/src/python/txtai/database/base.py b/src/python/txtai/database/base.py
index 18f7e7c0..0c30fc79 100644
--- a/src/python/txtai/database/base.py
+++ b/src/python/txtai/database/base.py
@@ -3,6 +3,7 @@ Database module
"""
import logging
+import re
import types
from .encoder import EncoderFactory
@@ -149,9 +150,10 @@ class Database:
if "select" in query and similarity:
for x in range(len(similarity)):
- token = f"{Token.SIMILAR_TOKEN}{x}"
- if where and token in where:
- where = where.replace(token, self.embed(similarity, x))
+ # Match the whole token, so that __SIMILAR__1 doesn't match the start of __SIMILAR__10
+ token = re.compile(rf"{Token.SIMILAR_TOKEN}{x}(?!\d)")
+ if where and token.search(where):
+ where = token.sub(self.embed(similarity, x), where)
elif similarity:
# Not a SQL query, load similarity results, if any
diff --git a/src/python/txtai/graph/query.py b/src/python/txtai/graph/query.py
index f294ae22..65ba33f1 100644
--- a/src/python/txtai/graph/query.py
+++ b/src/python/txtai/graph/query.py
@@ -155,8 +155,9 @@ class Query:
attribute = f"match_{x}"
clause = f"{node}.{attribute} > 0"
- # Replace placeholder with search results
- query = query.replace(f"{Query.SIMILAR}{x}", f"{clause}")
+ # Replace placeholder with search results, matching the whole placeholder so that
+ # __SIMILAR__1 doesn't match the start of __SIMILAR__10
+ query = re.sub(rf"{Query.SIMILAR}{x}(?!\d)", clause, query)
# Add uids and scores
for uid, score in result:
diff --git a/test/python/testdatabase/testrdbms.py b/test/python/testdatabase/testrdbms.py
index aa0a3eec..98148ba8 100644
--- a/test/python/testdatabase/testrdbms.py
+++ b/test/python/testdatabase/testrdbms.py
@@ -835,6 +835,22 @@ class Common:
)
self.assertEqual({row["text"] for row in result}, {self.data[1], self.data[4]})
+ def testSQLManySimilar(self):
+ """
+ Test a query with more than 10 similar clauses
+ """
+
+ words = ["apple", "banana", "cherry", "date", "elder", "fig", "grape", "honey", "ice", "jack", "kiwi", "lemon"]
+
+ embeddings = Embeddings({"keyword": True, "content": self.backend})
+ embeddings.index([(uid, f"{word} pie", None) for uid, word in enumerate(words)])
+
+ where = " or ".join(f"similar('{word}')" for word in words[:11])
+ results = embeddings.search(f"select id from txtai where {where}", 20)
+ self.assertEqual(sorted(int(x["id"]) for x in results), list(range(11)))
+
+ embeddings.close()
+
def testSparse(self):
"""
Test sparse vector search
diff --git a/test/python/testgraph.py b/test/python/testgraph.py
index 57e4ec9d..c99255f7 100644
--- a/test/python/testgraph.py
+++ b/test/python/testgraph.py
@@ -658,6 +658,20 @@ class TestGraph(unittest.TestCase):
self.assertEqual(sorted(results.scan()), [0, 1, 2])
self.assertEqual(results.edgecount(), 2)
+ def testSearchManySimilar(self):
+ """
+ Test a graph query with more than 10 similar clauses
+ """
+
+ words = ["apple", "banana", "cherry", "date", "elder", "fig", "grape", "honey", "ice", "jack", "kiwi", "lemon"]
+
+ embeddings = Embeddings({"keyword": True, "content": True, "graph": True})
+ embeddings.index([(uid, f"{word} pie", None) for uid, word in enumerate(words)])
+
+ where = " OR ".join(f"SIMILAR(A, '{word}')" for word in words[:11])
+ results = embeddings.search(f"MATCH (A) WHERE {where} RETURN A.id", 20)
+ self.assertEqual(sorted(x["A.id"] for x in results), list(range(11)))
+
def testSearchNoContent(self):
"""
Test a similar clause with content disabled