Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Escape literal SQL wildcard characters in term expansion (#1258)

LimbC-Ce7894cdb00c8
diff --git a/src/python/txtai/scoring/terms.py b/src/python/txtai/scoring/terms.py
index b20d5db1..26011636 100644
--- a/src/python/txtai/scoring/terms.py
+++ b/src/python/txtai/scoring/terms.py
@@ -37,7 +37,7 @@ class Terms:
INSERT_TERM = "INSERT OR REPLACE INTO terms VALUES (?, ?, ?)"
SELECT_TERMS = "SELECT ids, freqs FROM terms WHERE term = ?"
- WILDCARD_TERMS = "SELECT term FROM terms WHERE term LIKE ?"
+ WILDCARD_TERMS = "SELECT term FROM terms WHERE term LIKE ? ESCAPE '\\'"
# Documents table
CREATE_DOCUMENTS = """
@@ -462,7 +462,8 @@ class Terms:
if Terms.ASTERISK in term:
# Require a prefix or suffix
if term.replace(Terms.ASTERISK, "").strip():
- term = term.replace(Terms.ASTERISK, "%")
+ # Escape literal LIKE metacharacters before joining the wildcard segments.
+ term = "%".join(part.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") for part in term.split(Terms.ASTERISK))
result = self.cursor.execute(Terms.WILDCARD_TERMS, [term])
results.extend([t for t, in result])
else:
diff --git a/test/python/testscoring/testkeyword.py b/test/python/testscoring/testkeyword.py
index 50ffbe46..7ad82a91 100644
--- a/test/python/testscoring/testkeyword.py
+++ b/test/python/testscoring/testkeyword.py
@@ -164,6 +164,38 @@ class TestKeyword(unittest.TestCase):
self.assertEqual(scoring.count(), 0)
self.assertEqual(scoring.search("bear", 1), [])
+ def testWildcardLiteralCharacters(self):
+ """
+ Test that only asterisks act as wildcards in keyword queries
+ """
+
+ data = ["report_2026", "reportX2026", "rate%2026", "rateX2026", r"path\_2026", r"path\X2026", "path_2026", "plain2026", "plain2027"]
+ queries = [
+ ("report_*", {0}),
+ ("rate%*", {2}),
+ ("*%2026", {2}),
+ ("*_2026", {0, 4, 6}),
+ (r"path\_*", {4}),
+ (r"path\*", {4, 5}),
+ ("plain*", {7, 8}),
+ ("pl**2026", {7}),
+ ("*2027", {8}),
+ ("rate%2026", {2}),
+ ("report_2026", {0}),
+ ("*", set()),
+ ]
+ for method in ["bm25", "tfidf", "sif"]:
+ scoring = ScoringFactory.create({"method": method, "terms": True, "tokenizer": {"whitespace": True}})
+ try:
+ scoring.index([(uid, text, None) for uid, text in enumerate(data)])
+ for query, expected in queries:
+ with self.subTest(method=method, query=query):
+ results = scoring.search(query, len(data))
+ self.assertEqual({uid for uid, _ in results}, expected)
+ self.assertEqual(len(results), len(expected))
+ finally:
+ scoring.close()
+
def testDeleteUnknownId(self):
"""
Test that deleting an id that was never indexed is a no-op, not a crash