💡 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
Weight cluster avg() by the non-NULL count of the averaged column (#1434)
digit504fb2213deb68
diff --git a/src/python/txtai/database/sql/aggregate.py b/src/python/txtai/database/sql/aggregate.pyindex 2f8d3392..0f499786 100644--- a/src/python/txtai/database/sql/aggregate.py+++ b/src/python/txtai/database/sql/aggregate.py@@ -76,15 +76,17 @@ class Aggregate(SQL):return aggregates- def avg(self, values, counts):+ def avg(self, column, values, counts):"""Combines per-shard/per-group average values into a single average, weighted by a- matching count(*) column when one was selected. Without it, there is no way to- recombine the averages correctly, so this raises instead of returning a wrong number.+ matching count(col) column when one was selected. count(col) only counts the rows where+ col is not NULL, which are the rows avg(col) is computed over. Without it, there is no way+ to recombine the averages correctly, so this raises instead of returning a wrong number.Args:+ column: avg column namevalues: list of per-shard/per-group average values- counts: list of matching count(*) values, or None+ counts: list of matching count(col) values, or NoneReturns:combined average@@ -94,7 +96,7 @@ class Aggregate(SQL):return values[0]if not counts or sum(counts) == 0:- raise SQLError("avg() requires a count(*) column to combine results from multiple shards")+ raise SQLError(f"{column} requires a count({column[4:]} column to combine results from multiple shards")return sum(value * count for value, count in zip(values, counts)) / sum(counts)@@ -118,8 +120,9 @@ class Aggregate(SQL):else:results = [results]- # Column providing the row count each group's values were computed over, used to weight avg() columns- countcolumn = next((column for column in columns if column.lower() == "count(*)"), None)+ # Map each avg(col) column to its count(col) column, the non-NULL row count used to weight it+ countnames = {column[6:]: column for column in columns if column.lower().startswith("count(")}+ countcolumns = {column: countnames.get(column[4:]) for column in aggcolumns if column.lower().startswith("avg(")}# Compute column valuesrows = []@@ -130,8 +133,9 @@ class Aggregate(SQL):if column in aggcolumns:# Calculate aggregate value, skip NULLs from shards with no matching rowsmatches = [r for r in result if r[column] is not None]+ countcolumn = countcolumns.get(column)values, counts = [r[column] for r in matches], [r[countcolumn] for r in matches] if countcolumn else None- row[column] = (self.avg(values, counts) if column.lower().startswith("avg(") else aggcolumns[column](values)) if values else None+ row[column] = (self.avg(column, values, counts) if column in countcolumns else aggcolumns[column](values)) if values else Noneelse:# Non aggregate column value repeat, use first valuerow[column] = result[0][column]diff --git a/test/python/testapi/testcluster.py b/test/python/testapi/testcluster.pyindex 62236fff..98aa53e7 100644--- a/test/python/testapi/testcluster.py+++ b/test/python/testapi/testcluster.py@@ -49,9 +49,9 @@ class RequestHandler(BaseHTTPRequestHandler):response = [{"count(*)": 12, "txt": "This is a test"}, {"count(*)": 14, "txt": "And another test"}]else:if self.server.server_port == 8002:- response = [{"count(*)": 12, "min(indexid)": 0, "max(indexid)": 11, "avg(indexid)": 6.3}]+ response = [{"count(*)": 12, "count(indexid)": 12, "min(indexid)": 0, "max(indexid)": 11, "avg(indexid)": 6.3}]else:- response = [{"count(*)": 16, "min(indexid)": 2, "max(indexid)": 14, "avg(indexid)": 6.7}]+ response = [{"count(*)": 16, "count(indexid)": 16, "min(indexid)": 2, "max(indexid)": 14, "avg(indexid)": 6.7}]elif self.path.startswith("/search"):response = [{"id": 4, "score": 0.40}]else:@@ -284,10 +284,10 @@ class TestCluster(unittest.TestCase):Test cluster SQL statement"""- query = urllib.parse.quote("select count(*), min(indexid), max(indexid), avg(indexid) from txtai where text='This is a test'")+ query = urllib.parse.quote("select count(*), count(indexid), min(indexid), max(indexid), avg(indexid) from txtai where text='This is a test'")self.assertEqual(self.client.get(f"search?query={query}").json(),- [{"count(*)": 28, "min(indexid)": 0, "max(indexid)": 14, "avg(indexid)": 182.8 / 28}],+ [{"count(*)": 28, "count(indexid)": 28, "min(indexid)": 0, "max(indexid)": 14, "avg(indexid)": 182.8 / 28}],)query = urllib.parse.quote("select count(*), text txt from txtai group by txt order by count(*) desc")diff --git a/test/python/testdatabase/testsql.py b/test/python/testdatabase/testsql.pyindex 89ddbb7d..f8d2595b 100644--- a/test/python/testdatabase/testsql.py+++ b/test/python/testdatabase/testsql.py@@ -43,25 +43,49 @@ class TestSQL(unittest.TestCase):def testAggregateAvg(self):"""- Test Aggregate combines avg() results as a count(*)-weighted mean, not an unweighted+ Test Aggregate combines avg() results as a count()-weighted mean, not an unweightedaverage of averages"""aggregate = Aggregate()# 2 rows averaging 100 and 8 rows averaging 10 must combine to the true weighted mean, 28- query = "select count(*), avg(price) from txtai"- results = [{"count(*)": 2, "avg(price)": 100.0}, {"count(*)": 8, "avg(price)": 10.0}]- self.assertEqual(aggregate(query, results), [{"count(*)": 10, "avg(price)": 28.0}])+ query = "select count(price), avg(price) from txtai"+ results = [{"count(price)": 2, "avg(price)": 100.0}, {"count(price)": 8, "avg(price)": 10.0}]+ self.assertEqual(aggregate(query, results), [{"count(price)": 10, "avg(price)": 28.0}])# A single shard's average passes through unchangedself.assertEqual(aggregate("select avg(price) from txtai", [{"avg(price)": 42.0}]), [{"avg(price)": 42.0}])- # Combining averages from multiple shards with no count(*) to weight by cannot be done+ # Combining averages from multiple shards with no count() to weight by cannot be done# correctly, so it must raise rather than return an unweighted, silently wrong resultwith self.assertRaises(SQLError):aggregate("select avg(price) from txtai", [{"avg(price)": 100.0}, {"avg(price)": 10.0}])+ def testAggregateAvgNull(self):+ """+ Test Aggregate weights avg() by the non-NULL count of the averaged column+ """++ aggregate = Aggregate()++ # Shard A has prices [100, NULL], shard B has eight prices of 10, the true average is 180 / 9 = 20+ query = "select count(*), count(price), avg(price) from txtai"+ results = [{"count(*)": 2, "count(price)": 1, "avg(price)": 100.0}, {"count(*)": 8, "count(price)": 8, "avg(price)": 10.0}]+ self.assertEqual(aggregate(query, results), [{"count(*)": 10, "count(price)": 9, "avg(price)": 20.0}])++ # Shard A has x priced [100, NULL, NULL], shard B has x priced [10, 10, 10], the true average is 130 / 4 = 32.5+ query = "select text, count(*), count(price), avg(price) from txtai group by text"+ results = [+ {"text": "x", "count(*)": 3, "count(price)": 1, "avg(price)": 100.0},+ {"text": "x", "count(*)": 3, "count(price)": 3, "avg(price)": 10.0},+ ]+ self.assertEqual(aggregate(query, results), [{"text": "x", "count(*)": 6, "count(price)": 4, "avg(price)": 32.5}])++ # count(*) alone cannot weight avg() correctly when the averaged column has NULLs+ with self.assertRaises(SQLError):+ aggregate("select count(*), avg(price) from txtai", [{"count(*)": 2, "avg(price)": 100.0}, {"count(*)": 8, "avg(price)": 10.0}])+def testAggregateCase(self):"""Test Aggregate combines aggregate columns written in any case