Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Fix graph similar() clause truncating text with commas and dropping apostrophes (#1376)

Muneeb Ullah3b61a56de6c5
diff --git a/src/python/txtai/graph/query.py b/src/python/txtai/graph/query.py
index 2c6ff812..f294ae22 100644
--- a/src/python/txtai/graph/query.py
+++ b/src/python/txtai/graph/query.py
@@ -4,6 +4,7 @@ Query module
import logging
import re
+from shlex import shlex
try:
from grandcypher import GrandCypher
@@ -108,12 +109,15 @@ class Query:
offset = match.group(1)
# Parse similar clauses
- for x, match in enumerate(re.finditer(r"similar\((.+?)\)", query, flags=re.DOTALL | re.IGNORECASE)):
+ for x, match in enumerate(re.finditer(r"""similar\(((?:"[^"]*"|'[^']*'|[^)'"])+)\)""", query, flags=re.DOTALL | re.IGNORECASE)):
# Replace similar clause with placeholder
query = query.replace(match.group(0), f"{Query.SIMILAR}{x}")
- # Parse similar clause parameters
- params = [param.strip().replace("'", "").replace('"', "") for param in match.group(1).split(",")]
+ # Parse similar clause parameters, commas inside quotes are kept
+ params = shlex(match.group(1), posix=True)
+ params.whitespace, params.whitespace_split = ",", True
+ params = [param.strip() for param in params]
+
nodes.append(params[0])
similar.append(params[1:])
diff --git a/test/python/testgraph.py b/test/python/testgraph.py
index 14733793..57e4ec9d 100644
--- a/test/python/testgraph.py
+++ b/test/python/testgraph.py
@@ -11,7 +11,7 @@ from unittest.mock import patch
from txtai.archive import ArchiveFactory
from txtai.embeddings import Embeddings
-from txtai.graph import Graph, GraphFactory
+from txtai.graph import Graph, GraphFactory, Query
from txtai.graph.topics import Topics
from txtai.serialize import SerializeFactory
@@ -675,6 +675,45 @@ class TestGraph(unittest.TestCase):
results = embeddings.search("MATCH (A) WHERE SIMILAR(A, 'apple') RETURN A.id ORDER BY A.id")
self.assertEqual([x["A.id"] for x in results], [0, 1])
+ def testSearchQuoted(self):
+ """
+ Test similar clauses with quoted text containing commas, quotes and parentheses
+ """
+
+ # Create an index for the list of text
+ self.embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])
+
+ for text in ["feel good story, (really)", 'feel "good" story']:
+ results = self.embeddings.search(
+ f"""
+ MATCH P=(A)-[]->()
+ WHERE SIMILAR(A, '{text}', 5)
+ RETURN A
+ ORDER BY A.score DESC
+ LIMIT 1
+ """,
+ graph=True,
+ )
+ self.assertEqual(list(results.scan())[0], 4)
+
+ def testSearchQuotedParse(self):
+ """
+ Test parsing of similar clause parameters with quotes, whitespace and multiple clauses
+ """
+
+ query = Query()
+
+ parse = query.parse("MATCH (A) WHERE similar(A, 'x'\n) RETURN A")
+ self.assertEqual(parse["similar"], [["x"]])
+
+ parse = query.parse("MATCH (A), (B) WHERE SIMILAR(A, \"it's, ok\", 5) AND SIMILAR(B, 'a)b', 3) RETURN A")
+ self.assertEqual(parse["nodes"], ["A", "B"])
+ self.assertEqual(parse["similar"], [["it's, ok", "5"], ["a)b", "3"]])
+
+ parse = query.parse("MATCH (A) WHERE SIMILAR(A, 'a, (b', 3) AND SIMILAR(A, 'c', 2) RETURN A")
+ self.assertEqual(parse["query"], "MATCH (A) WHERE __SIMILAR__0 AND __SIMILAR__1 RETURN A")
+ self.assertEqual(parse["similar"], [["a, (b", "3"], ["c", "2"]])
+
def testSearchSkip(self):
"""
Test a SKIP clause with a similar clause