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(database): don't drop rows when sorting or grouping by a JSON field (#1238)

Serhii Zghama2e8a3d789293
diff --git a/src/python/txtai/database/rdbms.py b/src/python/txtai/database/rdbms.py
index 3deadf8f..6ff50f74 100644
--- a/src/python/txtai/database/rdbms.py
+++ b/src/python/txtai/database/rdbms.py
@@ -186,8 +186,9 @@ class RDBMS(Database):
if indexids:
select = f"{self.resolve('indexid')}, {self.resolve('score')}"
- # Use JOIN when documents table is used to utilize indexes, default to LEFT JOIN
- join = "JOIN" if any(x and self.jsonprefix() in x for x in [where, groupby, orderby]) else "LEFT JOIN"
+ # Use JOIN when a JSON field is filtered, since that filter already excludes rows without a
+ # documents row. GROUP BY/ORDER BY don't filter, so they keep the LEFT JOIN.
+ join = "JOIN" if where and self.jsonprefix() in where else "LEFT JOIN"
# Build query text
query = Statement.TABLE_CLAUSE % (select, join)
diff --git a/test/python/testdatabase/testrdbms.py b/test/python/testdatabase/testrdbms.py
index 1d576885..5a269daa 100644
--- a/test/python/testdatabase/testrdbms.py
+++ b/test/python/testdatabase/testrdbms.py
@@ -654,6 +654,24 @@ class Common:
self.assertEqual(result["text"], self.data[4])
+ def testSortMixed(self):
+ """
+ Test sorting and grouping by a JSON field with mixed text and document data
+ """
+
+ # Mix plain text, which has no documents table row, with a document that has a JSON field
+ embeddings = Embeddings({"keyword": True, "content": self.backend})
+ embeddings.index([(0, self.data[0], None), (1, {"text": self.data[1], "length": 5}, None)])
+
+ # Sorting must not change which rows come back
+ self.assertEqual(sorted(x["id"] for x in embeddings.search("select id from txtai order by length")), ["0", "1"])
+
+ # Grouping keeps a null group for rows missing the field
+ self.assertIn({"length": None, "total": 1}, embeddings.search("select length, count(*) as total from txtai group by length"))
+
+ # Filtering on the field still drops those rows
+ self.assertEqual([x["id"] for x in embeddings.search("select id from txtai where length is not null")], ["1"])
+
def testSQL(self):
"""
Test running a SQL query