Support GROUP BY on Nested JSONB Fields in Flat Postgres Collections #247
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Background
Nested collections in Postgres already support GROUP BY on nested fields within JSONB documents using dot notation:
Problem
Flat Postgres collections did not support GROUP BY on nested JSONB fields. The FlatPostgresFieldTransformer was missing logic to handle JsonIdentifierExpression when fields were unnested, causing:
Solution
When you UNNEST a JSONB array field and then GROUP BY it, there are two ways the SQL can reference that field:
Without the Fix (JSONB Accessor - Wrong)
-- UNNEST creates a column alias
jsonb_array_elements("props" -> 'colors') AS p1(props_colors_encoded)-- But GROUP BY was still using the JSONB accessor
GROUP BY "props" -> 'colors'Problem:
"props" -> 'colors'returns the entire array["Blue", "Green"], not the individual unnested values.Result: Groups by entire arrays →
["Blue", "Green"],["Black"],["Orange", "Blue"]With the Fix (Direct Column Reference - Correct)
-- UNNEST creates a column alias
jsonb_array_elements("props" -> 'colors') AS p1(props_colors_encoded)-- GROUP BY now references the unnested column directly
GROUP BY "props_colors_encoded"So, we've added unnest-aware logic in
FlatPostgresFieldTransformer.visit(JsonIdentifierExpression)to check thepgColMappingand return direct column references for unnested fields instead of JSONB accessors.Usage from Entity Service
GROUP BY on scalar JSONB field:
GROUP BY on JSONB array field (with UNNEST):
Flat collections now behave consistently with nested collections for GROUP BY operations on JSONB fields.