Repository navigation
MLE-31969: Support special characters in column names when aggregating structured data - #711
prgs-rsingh wants to merge 2 commits into
Conversation
21b6067 to
9b5a269
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved column-name handling can create duplicate output columns, drop the wrong column, and leave nested group-by references unresolvable after sanitization.
3 open issues
What changed in this PR
This PR updates Flux’s shared structured-data import transformations to support column names containing special characters across Avro, delimited, JDBC, ORC, and Parquet imports.
Changes:
- Adds case-aware column reference resolution and backtick quoting.
- Moves sanitization before filtering and aggregation, and corrects single-column aggregation sort direction.
- Adds unit and integration coverage and documents the updated naming behavior.
| File | Description |
|---|---|
flux-cli/src/test/resources/delimited-files/special-column-names.csv |
Adds sample data with special-character column names. |
flux-cli/src/test/java/com/marklogic/flux/impl/importdata/StructuredDataParamsTest.java |
Tests transformations with special, sanitized, quoted, and nested references. |
flux-cli/src/test/java/com/marklogic/flux/impl/importdata/ImportDelimitedFilesTest.java |
Adds CLI aggregation and sanitization integration tests. |
flux-cli/src/test/java/com/marklogic/flux/impl/importdata/ColumnReferencesTest.java |
Tests quoting, case handling, and original-name resolution. |
flux-cli/src/test/java/com/marklogic/flux/api/DelimitedFilesImporterTest.java |
Adds API aggregation coverage with sanitization enabled. |
flux-cli/src/main/java/com/marklogic/flux/impl/importdata/StructuredDataParams.java |
Updates transformation order, column resolution, and array sorting. |
flux-cli/src/main/java/com/marklogic/flux/impl/importdata/ColumnReferences.java |
Introduces shared column-name resolution and quoting. |
flux-cli/src/main/java/com/marklogic/flux/api/StructuredDataImporter.java |
Updates Javadoc for sanitization order and aggregation naming. |
docs/import/structured-data/sanitizing-column-names.md |
Documents early sanitization, name references, and limitations. |
docs/import/structured-data/filtering-data.md |
Explains SQL backtick quoting and shell escaping. |
docs/import/structured-data/aggregating-rows.md |
Adds special-character examples and option syntax restrictions. |
Review effort: Balanced
| result; | ||
|
|
||
| return sanitizeColumnNames(applyDrop(sorted)); | ||
| return applyDrop(sorted, references); |
There was a problem hiding this comment.
This seems like a user error we don't need to guard against.
| String columnName = resolve(reference); | ||
| return columnNames.contains(columnName) ? quote(columnName) : reference; |
There was a problem hiding this comment.
Fixed in 166b884. When a path starts with a name wrapped in backticks, that name is now resolved through the original-to-sanitized mapping, and the rest of the path keeps the quoting it was given. So with simple, `home address`.city is passed to Spark as `home_address`.city.
Covered by ColumnReferencesTest.pathWithQuotedStructColumn and by StructuredDataParamsTest.fieldsInStructColumnWithSimpleStrategy, which groups by a field of a renamed struct column using both the quoted and unquoted forms.
| // The references are those of the columns read from the data source, even when this is called after | ||
| // grouping. That is intentional: it is what allows a column to be dropped via its original name. Any | ||
| // other name, such as that of an aggregation, is not a known reference and is passed to Spark as-is. | ||
| dataset = dataset.drop(columnsToDrop.stream().map(references::resolve).toArray(String[]::new)); |
There was a problem hiding this comment.
Sounds like above too - this is the user shooting themselves in the foot by picking overlapping column names for an aggregation.
9b5a269 to
12c26f2
Compare
Column names passed to --group-by, --aggregate, and --aggregate-order-by were handed to Spark APIs that parse their input, so a period was read as a path to a nested field and a space broke the generated array_sort expression. A period in any column, aggregated or not, was enough to fail every aggregation. A reference that matches a top-level column is now quoted with backticks. It is matched regardless of case unless spark.sql.caseSensitive is enabled, as that is how Spark resolves column names. In a path to a field in a struct column, only the name of the column is quoted. --column-name-strategy is now applied first instead of last. Every option sees the sanitized names, and the fields in an aggregation are named after the sanitized columns. The original name of a column is still accepted by every option, including in a path to a field in a struct column. An unknown 'group by' column is now reported as such, and the error for a failed aggregation includes the cause reported by Spark.
--aggregate-order-by on an aggregation of a single column sorted in the opposite direction to the one requested, as the 'ascending' flag passed to Spark's sort_array function was negated.
12c26f2 to
a720166
Compare


Summary
--group-by,--aggregate, and--aggregate-order-byfailed when a column name contained a period, a space, parentheses,%, or a similar character. This affectedimport-avro-files,import-delimited-files,import-jdbc,import-orc-files, andimport-parquet-files, which all shareStructuredDataParams.UNRESOLVED_COLUMN, even when that column was not referenced by an option. Flux callsfirst()on every non-aggregated column, and Spark read the name as a path to a nested field.--aggregate-order-byfailed withPARSE_SYNTAX_ERROR, because the name was inserted unquoted into anarray_sortSQL expression.--column-name-strategy simple(MLE-12345: PDPS-2211 Add --column-name-strategy for structured-data imports #678, not yet released) did not help, because it ran after the steps that failed.Changes
Commit 1: column references and sanitization order
Quoting column references:
spark.sql.caseSensitiveis enabled, which is how Spark itself resolves column names.--group-by address.cityfor Avro, ORC, or Parquet), only the name of the column is quoted and the rest is left for Spark to parse. The column may itself be wrapped in backticks, e.g.`Home Address`.city. Any other reference is passed to Spark unchanged.ColumnReferencesclass that has no dependency on the Spark Dataset API.Applying
--column-name-strategyfirst:--where,--group-by,--aggregate,--aggregate-order-by, and--drop, rather than after them.--group-by,--aggregate,--aggregate-order-by, and--dropstill accept the original name of a column, including in a path to a field in a struct column.--normalize-column-names; this uses--column-name-strategy simplefrom MLE-12345: PDPS-2211 Add --column-name-strategy for structured-data imports #678 instead, so that there is one way to rename columns.Error messages:
--group-bycolumn is now reported asUnable to group by '<name>'; cause: .... Because the column is now passed to Spark as aColumn, Spark no longer checks it until the aggregation runs, so without this a typo in--group-bywas reported as a failure to aggregate columns that were valid.FluxException. Previously, a problem with the--group-bycolumn surfaced as Spark's ownAnalysisException.Unable to aggregate columns: ...error now ends with the cause reported by Spark, without the query plan.Docs are updated:
aggregating-rows.md,filtering-data.md,sanitizing-column-names.md, and the javadoc forStructuredDataImporter#columnNameStrategy.Commit 2: sort direction of single-column aggregations
--aggregate-order-byon an aggregation of a single column sorted in the opposite direction to the one requested, because theascflag passed to Spark'ssort_arraywas negated. This has been the behavior since 2.1.0 and was found while testing this story.Behavior changes for existing jobs
These affect jobs that use the default strategy and should be covered by a release note.
--group-by orderidagainst a source columnOrderIdused to write the column twice, asorderidandOrderId. It is now written once, asOrderId. A--uri-templatethat used the name as typed, such as/x/{orderid}.json, must be updated to use the name in the data source, because the connector looks up template values in a case-sensitive manner. The same applies to--aggregate: fields in the aggregation are named after the source columns, and those columns are no longer also kept at the top level.--group-byand--aggregatethis used to write the column twice; it is now written once. In--dropit used to be ignored; the column is now dropped.--aggregate-order-bynow sorts in the requested direction (commit 2).--group-bycolumn and for a failed aggregation has changed, as described above.--group-byerrors. A problem with the--group-bycolumn, such as an unknown column or an invalid path into a struct column, used to be thrown as Spark'sorg.apache.spark.sql.AnalysisException. It is now thrown as aFluxExceptionwhose cause is that Spark exception. This only matters to users of the Java API who catch a specific exception type; the CLI reports the error either way.Behavior changes relative to #678
These only affect
--column-name-strategy simple, which has not been released.--aggregateis used as given and is no longer sanitized.--dropis applied, so dropping the offending column no longer avoids the error.collidingNamesCannotBeAvoidedByDroppingColumncaptures this.Item Nameanditem_name, now fail with--group-by, because Spark cannot tellItem_Nameanditem_nameapart. This is documented as a limitation and captured bysanitizedNamesDifferingOnlyByCase. The duplicate check inSimpleColumnNameSanitizeris left as it is.--group-byon a field in a struct column produces a column named after that field. Field names within a struct column are not sanitized, so a field namedZip Codenow produces a column namedZip Code, where it previously becameZip_Codebecause sanitization ran last. This is documented as a limitation.The
simplerule itself is unchanged.Testing
ColumnReferencesTest: unit tests for quoting and resolving references, including case handling and struct paths.StructuredDataParamsTest: runs the transformations against a local Spark session, with no MarkLogic required. It reads the test file with inferred types, asimport-delimited-filesdoes. Covers group-by, aggregation, ordering,--where,--drop, and the error messages for both strategies, plus struct columns.ImportDelimitedFilesTestandDelimitedFilesImporterTest: three end-to-end tests via the CLI and the API.The first two classes and
SimpleColumnNameSanitizerTestwere run locally against Spark 4.2.0.CI notes:
ExportFilesTest.withRedactionTransform. That test also fails ondevelopbuilds MLE-23140 Added docs for pipeline batch size #444 and MLE-23140 Added docs for pipeline batch size #445 and does not exercise code changed here. All of the tests added by this PR passed in that build, including the end-to-end tests.Questions for reviewers
--dropcan no longer be used to avoid a collision or empty-name error? For CSV, Avro, ORC, and Parquet sources the only workaround is to change the source file.SimpleColumnNameSanitizerignore case, so that names differing only by case are reported as a collision rather than failing in--group-by? That would also reject the no-grouping case, which works today.Out of scope
simplerule is not changed for TDE validity (MLE-27356): a name that starts with a digit or is longer than 128 characters is still not a valid TDE column name.concat(). A numeric column is therefore written as an array of strings and sorted as text, e.g.["10","100","9"]. This predates this PR and is not changed here.--aggregate-order-bycannot sort by a field within a struct column. This predates this PR.