This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
The following commit(s) were added to refs/heads/dev by this push:
new ee0fb0d72f [Docs][Transform-V2] Rewrite DataValidator documentation
(#13379)
ee0fb0d72f is described below
commit ee0fb0d72f67edbcd6caf08360fd354fa68e002f
Author: niumy <[email protected]>
AuthorDate: Fri Nov 27 07:17:09 2026 +0000
[Docs][Transform-V2] Rewrite DataValidator documentation (#13379)
Co-authored-by: muyue niu <[email protected]>
---
docs/en/transforms/data-validator.md | 524 ++++++++++++++++++++--------------
docs/zh/transforms/data-validator.md | 526 +++++++++++++++++++++--------------
2 files changed, 632 insertions(+), 418 deletions(-)
diff --git a/docs/en/transforms/data-validator.md
b/docs/en/transforms/data-validator.md
index 613a1f38c3..a0579eb294 100644
--- a/docs/en/transforms/data-validator.md
+++ b/docs/en/transforms/data-validator.md
@@ -1,207 +1,289 @@
# DataValidator
-> Data validation transform plugin
+## Support Those Engines
+
+> SeaTunnel Zeta<br/>
+> Flink<br/>
+> Spark
## Description
-The DataValidator transform validates field values according to configured
rules and handles validation failures based on the specified error handling
strategy. It supports multiple validation rule types including null checks,
range validation, length validation, and regex pattern matching.
+DataValidator checks field values against configurable validation rules. It is
a row-level quality gate: valid rows are passed through unchanged, and the
input schema is never modified. When a row fails any rule, the transform
applies the configured error handling policy: fail the job (`FAIL`, the
default), drop the row (`SKIP`), or convert the row into a structured error
record and route it to a dedicated error table (`ROUTE_TO_TABLE`).
+
+All configured fields of every row are validated (there is no fail-fast): a
row is invalid when at least one rule fails, and all failures of the row are
collected into the error messages.
## Options
-| name | type | required | default value |
-|-----------------|--------|----------|---------------|
-| row_error_handle_way| enum | no | FAIL |
-| row_error_handle_way.error_table | string | no | |
-| field_rules | array | yes (single-table mode) | |
-| table_match_regex | string | no | `.*` |
-| table_transform | array | no | - |
-| rule_match_mode | string | no | `FIRST_MATCH` |
+| Name | Type | Required | Default | Description |
+|------|------|----------|---------|-------------|
+| field_rules | Array<Map> | Conditional | - | Validation rules grouped
by field name. Required by the transform-level rule and by every
`table_transform` entry. |
+| row_error_handle_way | Enum | No | `FAIL` | What to do with an invalid row:
`FAIL`, `SKIP`, or `ROUTE_TO_TABLE`. |
+| row_error_handle_way.error_table | String | Conditional | - | Target table
for routed invalid rows when `row_error_handle_way` is `ROUTE_TO_TABLE`. |
+| table_match_regex | String | No | `.*` | Match upstream table paths to which
the transform-level rule applies. |
+| table_transform | Array<Map> | No | `[]` | Complete rules for
individual tables, selected by an exact `table_path`. |
+| rule_match_mode | Enum | No | `FIRST_MATCH` | Select the first matching
per-table rule, or apply all matching rules in order. See the duplicate-path
behavior below. |
+| common options | - | No | - | Common transform options such as
`plugin_input` and `plugin_output`. |
+
+### field_rules [Array<Map>]
+
+The validation rules. Without a nonempty `table_transform` list, `field_rules`
is required at the transform level; an empty `table_transform = []` does not
remove this requirement.
+
+Each entry describes the rules of one field and supports two equivalent shapes:
+
+- **Nested**: one entry per field, with a `rules` list inside:
+
+```hocon
+field_rules = [
+ {
+ field_name = "age"
+ rules = [
+ { rule_type = "NOT_NULL" },
+ { rule_type = "RANGE", min_value = "0", max_value = "150" }
+ ]
+ }
+]
+```
+
+- **Flat**: one entry per rule, with the rule parameters directly in the
entry. Multiple flat entries for the same field are merged into one field rule:
-### row_error_handle_way [enum]
+```hocon
+field_rules = [
+ { field_name = "age", rule_type = "NOT_NULL" },
+ { field_name = "age", rule_type = "RANGE", min_value = "0", max_value =
"150" }
+]
+```
-Error handling strategy when validation fails:
-- `FAIL`: Fail the entire task when validation errors occur
-- `SKIP`: Skip invalid rows and continue processing
-- `ROUTE_TO_TABLE`: Route invalid data to a specified error table
+Every entry must contain a nonblank `field_name` and either a `rule_type` or a
non-empty `rules` list; otherwise job submission fails with a validation error.
Rules for a field that is not present in the input schema are skipped with a
warning, and unknown rule types are ignored with a warning.
-**Note**: `ROUTE_TO_TABLE` mode only works with sinks that support multiple
tables. The sink must be capable of handling data routed to different table
destinations.
+The supported rule types:
-### row_error_handle_way.error_table [string]
+| rule_type | Parameters | Description |
+|-----------|------------|-------------|
+| `NOT_NULL` | custom_message | Fails when the value is `null`. |
+| `RANGE` | min_value, max_value, min_inclusive, max_inclusive, custom_message
| Fails when the value is outside the range. Both bounds are inclusive by
default. A `null` value passes this rule — combine it with `NOT_NULL` to reject
nulls. |
+| `LENGTH` | min_length, max_length, exact_length, custom_message | Checks the
length of strings, arrays and collections. `exact_length` is checked first,
then `min_length` / `max_length`. A `null` value passes this rule. |
+| `REGEX` | pattern (required), case_sensitive, custom_message | Matches the
value against a Java regular expression. Matching is case-sensitive by default.
|
+| `UDF` | function_name (required), custom_message | Runs a built-in or custom
validation function. Built-in: `EMAIL` (practical email validation based on
OWASP recommendations). |
-Target table name for routing invalid data when `row_error_handle_way` is set
to `ROUTE_TO_TABLE`. This option is not validated by the framework, but if it
is not configured in `ROUTE_TO_TABLE` mode, DataValidator cannot route invalid
rows and will skip them with a warning instead, so it should always be set when
using `ROUTE_TO_TABLE`.
+Notes on the rule parameters:
-#### Error Table Schema
+- **min_value / max_value**: compared as `BigDecimal` when both sides are
numeric, so the field type does not have to match the bound type; a value that
cannot be parsed as a number is compared by its string representation.
+- **min_inclusive / max_inclusive**: default `true` (closed range). Set to
`false` for an open bound.
+- **min_length / max_length / exact_length**: integers. String length is
counted in Java UTF-16 code units; array length is the number of elements (the
number of bytes for binary arrays); collection length is its size.
+- **case_sensitive**: default `true`.
+- **custom_message**: replaces the default error message of the rule. It
appears both in the exception message of `FAIL` mode and in the
`validation_errors` column of the error table.
+- Rule parameter values may be written as numbers or as numeric strings (for
example `min_length = 2` and `min_length = "2"` are equivalent).
-When using `ROUTE_TO_TABLE` mode, DataValidator automatically creates an error
table with a fixed schema to store validation failure data. The error table
contains the following fields:
+### row_error_handle_way [Enum]
-| Field Name | Data Type | Description |
-|------------|-----------|-------------|
-| source_table_id | STRING | Source table identifier that identifies the
originating table |
-| source_table_path | STRING | Source table path with complete table path
information |
-| original_data | STRING | JSON representation of the original data containing
the complete row that failed validation |
-| validation_errors | STRING | JSON array of validation error details
containing all failed fields and error information |
-| create_time | TIMESTAMP | Creation time of the validation error |
+What happens to a row that fails at least one rule:
-**Complete Error Table Record Example**:
-```json
-{
- "source_table_id": "users_table",
- "source_table_path": "database.users",
- "original_data": "{\"id\": 123, \"name\": null, \"age\": 200, \"email\":
\"invalid-email\"}",
- "validation_errors": "[{\"field_name\": \"name\", \"error_message\": \"Field
'name' cannot be null\"}, {\"field_name\": \"age\", \"error_message\": \"Field
'age' value 200 is not within range [0, 150]\"}, {\"field_name\": \"email\",
\"error_message\": \"Field 'email' does not match pattern
'^[\\\\w-\\\\.]+@([\\\\w-]+\\\\.)+[\\\\w-]{2,4}$'\"}]",
- "create_time": "2024-01-15T10:30:45"
-}
-```
+- `FAIL` (default): the transform throws a validation error and the job fails.
The exception message joins the error messages of all failed rules of the row.
+- `SKIP`: invalid rows are dropped; valid rows continue downstream.
+- `ROUTE_TO_TABLE`: invalid rows are converted into error records and routed
to the error table configured by `row_error_handle_way.error_table`. If no
error table is configured (or the value is blank), invalid rows are dropped
with a warning.
-**Data Routing Mechanism**:
-- Data that passes validation maintains the original schema and is routed to
the main output table
-- Data that fails validation is converted to the error table schema format
above and routed to the specified error table
-- Each validation failure row generates one record in the error table,
containing complete original data and detailed error information
+:::caution
+`ROUTE_TO_TABLE` requires a sink that supports multiple tables: the transform
produces the validated table plus the error table, and the sink has to write
both.
+:::
-### field_rules [array]
+### row_error_handle_way.error_table [String]
-Array of field validation rules. Each rule defines validation criteria for a
specific field.
+The table that receives the routed invalid rows. The value is either:
-A single-table config must set `field_rules`. With `table_transform`, every
entry declares its own `field_rules`; the transform level one is optional.
+- a plain table name without a dot — the error table is placed in the same
database/schema as the input table;
+- a path containing a dot (for example `error_db.error_data` or
`db.error_schema.error_data`) — used as the table path as-is.
-The `table_match_regex` option selects the tables the transform level rule
applies to (default `.*`), `table_transform` holds complete per-table rules
(`table_path` plus `field_rules`), and `rule_match_mode` (`FIRST_MATCH` or
`ALL_MATCH`) controls how duplicate `table_path` entries are evaluated. See
[Multi-Table Transform](transform-multi-table.md).
+Each routed row is an error record with the following fixed schema:
-#### Field Rule Structure
+| Column | Type | Description |
+|--------|------|-------------|
+| source_table_id | String | Full identifier of the table the row came from
(catalog.database.schema.table, with the parts that exist). |
+| source_table_path | String | Table path of the source table. |
+| original_data | String | JSON object of the complete original row. |
+| validation_errors | String | JSON array of `{field_name, error_message}`
objects, one per failed rule. |
+| create_time | LocalDateTime | When the error record was produced. |
-Each field rule contains:
-- `field_name`: Name of the field to validate
-- `rules`: Array of validation rules to apply (nested format), or individual
rule properties (flat format)
+### table_match_regex [String]
-#### Validation Rule Types
+A Java regular expression matched against the whole upstream table path, such
as `test.abc` or `database.schema.table`. The default `.*` matches all table
paths. This is the actual table path, not the dataset name in `plugin_input` or
`plugin_output`.
-##### NOT_NULL
-Validates that a field value is not null.
+This option selects the tables to which the transform-level rule applies. It
does not restrict explicit `table_transform` entries.
-Parameters:
-- `rule_type`: "NOT_NULL"
-- `custom_message` (optional): Custom error message
+### table_transform [Array<Map>]
-##### RANGE
-Validates that a numeric value is within a specified range.
+A list of per-table rules; the default is an empty list. Each entry must have
a nonblank `table_path` (an exact path, not a regular expression) in the form
`databaseName[.schemaName].tableName`, plus a complete single-table
DataValidator rule for that table: `field_rules` and an optional error handling
policy.
-Parameters:
-- `rule_type`: "RANGE"
-- `min_value` (optional): Minimum allowed value
-- `max_value` (optional): Maximum allowed value
-- `min_inclusive` (optional): Whether minimum value is inclusive (default:
true)
-- `max_inclusive` (optional): Whether maximum value is inclusive (default:
true)
-- `custom_message` (optional): Custom error message
+An entry declares its own `field_rules` and does not inherit the
transform-level `field_rules`. A matching entry takes precedence even when its
table does not match `table_match_regex`. The error handling policy is the
exception: see `Multi-Table Configuration` below.
-##### LENGTH
-Validates the length of string, array, or collection values.
+### rule_match_mode [Enum]
-Array length is the number of elements, including null elements. Nested arrays
-are measured by their outer length, and binary values by their number of bytes.
-String length uses Java UTF-16 code units; collection length uses its size.
-Null values pass this rule; combine it with `NOT_NULL` to reject nulls.
+Controls multiple entries with the same exact `table_path`:
-Parameters:
-- `rule_type`: "LENGTH"
-- `min_length` (optional): Minimum allowed length
-- `max_length` (optional): Maximum allowed length
-- `exact_length` (optional): Exact required length
-- `custom_message` (optional): Custom error message
+- Explicit `FIRST_MATCH`: use the first matching entry in list order.
+- Explicit `ALL_MATCH`: apply all matching entries in list order; the output
of an earlier matching entry becomes the input of the next matching entry for
the same table.
-##### REGEX
-Validates that a string value matches a regular expression pattern.
+Although the option's default is `FIRST_MATCH`, omitting the option rejects
duplicate `table_path` entries during transform initialization. Set it
explicitly if repeated paths are intentional. With unique paths, the default is
sufficient.
-Parameters:
-- `rule_type`: "REGEX"
-- `pattern`: Regular expression pattern (required)
-- `case_sensitive` (optional): Whether pattern matching is case sensitive
(default: true)
-- `custom_message` (optional): Custom error message
+### common options
-##### UDF (User Defined Function)
-Validates field values using custom business logic implemented as a User
Defined Function.
+Use `plugin_input` and `plugin_output` to connect this transform to upstream
and downstream plugins. See [Transform
Plugin](common-options/common-options.md) for common parameters.
-Parameters:
-- `rule_type`: "UDF"
-- `function_name`: Name of the UDF function to execute (required)
-- `custom_message` (optional): Custom error message
+## Multi-Table Configuration
-**Built-in UDF Functions:**
-- `EMAIL`: Validates email addresses using practical validation rules based on
OWASP recommendations
+For each input table, the effective rule is selected in this order:
-**Creating Custom UDF Functions:**
-To create a custom UDF function:
-1. Implement the `DataValidatorUDF` interface
-2. Use `@AutoService(DataValidatorUDF.class)` annotation
-3. Provide a unique `functionName()`
-4. Implement the `validate()` method with your custom logic
+1. Use the matching `table_transform` entry or entries, according to
`rule_match_mode`.
+2. Otherwise, apply the transform-level rule if one is configured (see
`field_rules`) and the table path matches `table_match_regex`.
+3. Otherwise, pass the table's rows through unchanged.
-### common options [string]
+In a `table_transform`-only configuration, unlisted tables pass through
unchanged. The presence of `field_rules` marks the transform-level rule as
configured: without it, the other transform-level options have no effect on the
field rules.
-Transform plugin common parameters, please refer to [Transform
Plugin](common-options/common-options.md) for details
+DataValidator has one option group that behaves differently:
`row_error_handle_way` and `row_error_handle_way.error_table` are error
handling **policies**. They are configured once at the transform level and also
apply to tables selected by a `table_transform` entry, unless the entry sets
its own value. This makes a single error table usable for every validated table.
+
+The following examples cover all three configuration shapes. See [Multi-Table
Transform](transform-multi-table.md) for the shared matching rules.
## Examples
-### Example 1: Basic Validation with FAIL Mode
+These complete batch configurations use FakeSource and Console. Install those
connectors in your SeaTunnel distribution before running a saved configuration
with `bin/seatunnel.sh --config <file> -e local`. The rows are fixed by the
`rows` option of FakeSource, so the expected outputs are deterministic.
+
+### Transform-level rules only, with ROUTE_TO_TABLE
+
+The input has six rows; three of them violate the rules (a `null` name, an age
of 200, and a malformed email). With `ROUTE_TO_TABLE`, the valid rows keep
flowing to the validated output while each invalid row is converted into an
error record and routed to `error_data`:
```hocon
+env {
+ job.mode = "BATCH"
+ parallelism = 1
+}
+
+source {
+ FakeSource {
+ plugin_output = "fake"
+ schema {
+ fields {
+ id = "int"
+ name = "string"
+ age = "int"
+ email = "string"
+ }
+ }
+ rows = [
+ { fields = [1, "John Doe", 25, "[email protected]"], kind = INSERT }
+ { fields = [2, "Jane Smith", 30, "[email protected]"], kind = INSERT }
+ { fields = [3, "Charlie Wilson", 32, "[email protected]"], kind =
INSERT }
+ { fields = [4, null, 30, "[email protected]"], kind = INSERT }
+ { fields = [5, "Bob Johnson", 200, "[email protected]"], kind = INSERT }
+ { fields = [6, "Alice Brown", 28, "invalid-email"], kind = INSERT }
+ ]
+ }
+}
+
transform {
DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "FAIL"
+ plugin_input = "fake"
+ plugin_output = "validated"
+ row_error_handle_way = "ROUTE_TO_TABLE"
+ row_error_handle_way.error_table = "error_data"
field_rules = [
{
field_name = "name"
rule_type = "NOT_NULL"
+ custom_message = "name must not be null"
},
{
field_name = "age"
rule_type = "RANGE"
- min_value = 0
- max_value = 150
+ min_value = "0"
+ max_value = "150"
},
{
field_name = "email"
rule_type = "REGEX"
pattern = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"
+ custom_message = "invalid email format"
}
]
}
}
+
+sink {
+ Console {
+ plugin_input = "validated"
+ }
+}
```
-### Example 2: Validation with SKIP Mode
+The `validated` output keeps rows 1–3 unchanged. The `error_data` table
receives three error records; for example the record for row 5 contains:
+
+| source_table_id | source_table_path | original_data | validation_errors |
create_time |
+|----------------|-------------------|--------------|------------------|-------------|
+| ... | fake | {"id":5,"name":"Bob
Johnson","age":200,"email":"[email protected]"} |
[{"field_name":"age","error_message":"Value 200 exceeds maximum 150"}] | ... |
+
+and the record for row 6 contains
`[{"field_name":"email","error_message":"invalid email format"}]` in
`validation_errors`, because the `custom_message` of the rule replaces the
default message.
+
+:::tip
+With `row_error_handle_way = "FAIL"` (the default) the same configuration
fails the job on the first invalid row; with `SKIP` the three invalid rows are
silently dropped and only rows 1–3 reach the sink.
+:::
+
+### Transform-level rule with per-table rules
+
+Each input table contains two valid rows. `test.abc` is validated by the
transform-level `field_rules`, while `test.xyz` uses its own `table_transform`
entry. The error handling policy (`FAIL`) is set once at the transform level
and applies to both tables.
+
+| Table | Effective field rules | Output rows |
+|-------|----------------------|-------------|
+| `test.abc` | Transform level: `name` NOT_NULL, `age` RANGE 0–150. | 2 |
+| `test.xyz` | Entry: `name` NOT_NULL, `email` REGEX. | 2 |
```hocon
-transform {
- DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "SKIP"
- field_rules = [
+env {
+ job.mode = "BATCH"
+ parallelism = 1
+}
+
+source {
+ FakeSource {
+ plugin_output = "fake"
+ tables_configs = [
{
- field_name = "name"
- rule_type = "NOT_NULL"
+ schema {
+ table = "test.abc"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "John Doe", 25, "[email protected]"], kind = INSERT }
+ { fields = [2, "Jane Smith", 30, "[email protected]"], kind = INSERT }
+ ]
},
{
- field_name = "name"
- rule_type = "LENGTH"
- min_length = 2
- max_length = 50
+ schema {
+ table = "test.xyz"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "Bob Johnson", 35, "[email protected]"], kind = INSERT
}
+ { fields = [2, "Alice Brown", 28, "[email protected]"], kind =
INSERT }
+ ]
}
]
}
}
-```
-
-### Example 3: Validation with ROUTE_TO_TABLE Mode
-```hocon
transform {
DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "ROUTE_TO_TABLE"
- row_error_handle_way.error_table = "error_data"
+ plugin_input = "fake"
+ plugin_output = "validated"
+ row_error_handle_way = "FAIL"
+ // Applies to every table that is not covered by a table_transform entry.
field_rules = [
{
field_name = "name"
@@ -210,136 +292,160 @@ transform {
{
field_name = "age"
rule_type = "RANGE"
- min_value = 0
- max_value = 150
+ min_value = "0"
+ max_value = "150"
}
]
- }
-}
-```
-
-**Note**: When using `ROUTE_TO_TABLE`, ensure your sink connector supports
multiple tables. Valid data will be sent to the main output table, while
invalid data will be routed to the specified error table.
-
-In this example:
-- Data that passes validation will maintain the original schema (containing
name, age, etc. fields) and be sent to the main output table
-- Data that fails validation will be converted to the error table schema
(containing source_table_id, source_table_path, original_data,
validation_errors, create_time fields) and routed to the "error_data" table
-### Example 4: Nested Rules Format
-
-```hocon
-transform {
- DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "FAIL"
- field_rules = [
+ table_transform = [
{
- field_name = "name"
- rules = [
+ table_path = "test.xyz"
+ field_rules = [
{
+ field_name = "name"
rule_type = "NOT_NULL"
- custom_message = "Name is required"
},
{
- rule_type = "LENGTH"
- min_length = 2
- max_length = 50
- custom_message = "Name must be between 2 and 50 characters"
+ field_name = "email"
+ rule_type = "REGEX"
+ pattern = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"
}
]
}
]
}
}
+
+sink {
+ Console {
+ plugin_input = "validated"
+ }
+}
```
-### Example 5: Email Validation using Built-in UDF
+### Per-table rules only
+
+There is no transform-level `field_rules`: every table is validated by its own
`table_transform` entry, and any other table would pass through unchanged. The
error handling policy is still configured at the transform level and applies to
every validated table.
```hocon
+env {
+ job.mode = "BATCH"
+ parallelism = 1
+}
+
+source {
+ FakeSource {
+ plugin_output = "fake"
+ tables_configs = [
+ {
+ schema {
+ table = "test.abc"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "John Doe", 25, "[email protected]"], kind = INSERT }
+ { fields = [2, "Jane Smith", 30, "[email protected]"], kind = INSERT }
+ ]
+ },
+ {
+ schema {
+ table = "test.xyz"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "Bob Johnson", 35, "[email protected]"], kind = INSERT
}
+ { fields = [2, "Alice Brown", 28, "[email protected]"], kind =
INSERT }
+ ]
+ }
+ ]
+ }
+}
+
transform {
DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
+ plugin_input = "fake"
+ plugin_output = "validated"
row_error_handle_way = "FAIL"
- field_rules = [
+ table_transform = [
{
- field_name = "email"
- rule_type = "UDF"
- function_name = "EMAIL"
- custom_message = "Invalid email address format"
+ table_path = "test.abc"
+ field_rules = [
+ {
+ field_name = "name"
+ rule_type = "NOT_NULL"
+ },
+ {
+ field_name = "age"
+ rule_type = "RANGE"
+ min_value = "0"
+ max_value = "150"
+ }
+ ]
+ },
+ {
+ table_path = "test.xyz"
+ field_rules = [
+ {
+ field_name = "name"
+ rule_type = "NOT_NULL"
+ },
+ {
+ field_name = "email"
+ rule_type = "REGEX"
+ pattern = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"
+ }
+ ]
}
]
}
}
+
+sink {
+ Console {
+ plugin_input = "validated"
+ }
+}
```
-## UDF Development Guide
+Both tables are valid in this input, so all four rows pass validation. An
invalid row in `test.abc` would fail the job, because the transform-level
`row_error_handle_way = "FAIL"` policy applies even without a transform-level
`field_rules`; a table without an entry would pass through without validation.
-### Creating Custom UDF Functions
+## Developing a Custom UDF Rule
-To create a custom validation UDF function, follow these steps:
+Besides the built-in `EMAIL` function, you can add your own validation
function:
-#### 1. Implement the DataValidatorUDF Interface
+1. Implement the `DataValidatorUDF` interface
(`org.apache.seatunnel.transform.validator.udf.DataValidatorUDF`), returning a
unique `functionName()` and the `validate()` logic:
```java
-package com.example.validator;
-
-import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
-import org.apache.seatunnel.transform.validator.ValidationContext;
-import org.apache.seatunnel.transform.validator.ValidationResult;
-import org.apache.seatunnel.transform.validator.udf.DataValidatorUDF;
-import com.google.auto.service.AutoService;
-
@AutoService(DataValidatorUDF.class)
public class PhoneValidator implements DataValidatorUDF {
@Override
public String functionName() {
- return "PHONE_VALIDATOR";
+ return "PHONE";
}
@Override
public ValidationResult validate(
Object value, SeaTunnelDataType<?> dataType, ValidationContext
context) {
-
if (value == null) {
return ValidationResult.success();
}
-
- String phone = value.toString().trim();
-
- // Custom phone validation logic
- if (phone.matches("^\\+?[1-9]\\d{1,14}$")) {
- return ValidationResult.success();
- } else {
- return ValidationResult.failure("Invalid phone number format: " +
phone);
- }
- }
-
- @Override
- public String getDescription() {
- return "Validates international phone number format";
+ return value.toString().trim().matches("^\\+?[1-9]\\d{1,14}$")
+ ? ValidationResult.success()
+ : ValidationResult.failure("Invalid phone number format: " +
value);
}
}
```
-#### 2. Register the UDF
-
-The UDF is automatically registered using the
`@AutoService(DataValidatorUDF.class)` annotation. This uses Java's
ServiceLoader mechanism to discover and load UDF implementations at runtime.
-
-#### 3. Package and Deploy
-
-1. Compile your UDF class and package it into a JAR file
-2. Place the JAR file in the SeaTunnel classpath
-3. The UDF will be automatically discovered and available for use
-
-
-**Usage Example**:
-```hocon
-{
- field_name = "email"
- rule_type = "UDF"
- function_name = "EMAIL"
- custom_message = "Please provide a valid email address"
-}
-```
+2. Annotate the class with `@AutoService(DataValidatorUDF.class)` so it is
discovered by the Java `ServiceLoader` mechanism.
+3. Package the compiled class into a JAR and put it on the SeaTunnel
classpath; the function is then available by its `function_name`.
diff --git a/docs/zh/transforms/data-validator.md
b/docs/zh/transforms/data-validator.md
index b01bdd0be3..a5145e63f6 100644
--- a/docs/zh/transforms/data-validator.md
+++ b/docs/zh/transforms/data-validator.md
@@ -1,206 +1,289 @@
-# 数据验证
+# 数据校验
-> DataValidator:按规则校验字段值,并处理不符合要求的数据
+## 支持的引擎
-## 描述
+> SeaTunnel Zeta<br/>
+> Flink<br/>
+> Spark
-DataValidator
转换插件会根据配置规则校验字段值,并按照指定的错误处理策略处理验证失败的数据。它支持空值检查、范围验证、长度验证和正则表达式匹配等多种校验方式。
+## 描述
-## 选项
+DataValidator
根据可配置的校验规则检查字段值。它是一个行级数据质量闸门:校验通过的行原样传递,且输入模式永远不会被修改。当一行违反任意规则时,转换按配置的错误处理策略处理该行:使作业失败(`FAIL`,默认)、丢弃该行(`SKIP`),或将该行转换为结构化的错误记录并路由到专用的错误表(`ROUTE_TO_TABLE`)。
-| 名称 | 类型 | 是否必需 | 默认值 |
-|-----------------|--------|----------|--------|
-| row_error_handle_way| enum | 否 | FAIL |
-| row_error_handle_way.error_table | string | 否 | |
-| field_rules | array | 是(单表模式) | |
-| table_match_regex | string | 否 | `.*` |
-| table_transform | array | 否 | - |
-| rule_match_mode | string | 否 | `FIRST_MATCH` |
+每一行的所有已配置字段都会被校验(不存在快速失败):只要至少一条规则失败,该行即为无效,且该行的全部失败信息都会收集到错误消息中。
-### row_error_handle_way [enum]
+## 属性
-验证失败时的错误处理策略:
-- `FAIL`: 当验证错误发生时,整个任务失败
-- `SKIP`: 跳过无效行并继续处理
-- `ROUTE_TO_TABLE`: 将无效数据路由到指定的错误表
+| 名称 | 类型 | 是否必须 | 默认值 | 描述 |
+|------|------|----------|--------|------|
+| field_rules | Array<Map> | 条件必需 | - | 按字段名分组的校验规则。转换级规则和每个
`table_transform` 条目都必填。 |
+| row_error_handle_way | Enum | 否 | `FAIL` | 对无效行的处理方式:`FAIL`、`SKIP` 或
`ROUTE_TO_TABLE`。 |
+| row_error_handle_way.error_table | String | 条件必需 | - |
`row_error_handle_way` 为 `ROUTE_TO_TABLE` 时接收无效行的目标表。 |
+| table_match_regex | String | 否 | `.*` | 匹配转换级规则所应用的上游表路径。 |
+| table_transform | Array<Map> | 否 | `[]` | 通过精确的 `table_path`
为各表指定完整规则。 |
+| rule_match_mode | Enum | 否 | `FIRST_MATCH` |
选择第一条匹配的表级规则,或按顺序执行所有匹配的规则。重复路径的行为见下文。 |
+| common options | - | 否 | - | `plugin_input`、`plugin_output` 等转换插件通用参数。 |
-**注意**:`ROUTE_TO_TABLE` 模式仅适用于支持多表写入的 sink 连接器。sink 必须具备把数据路由到不同目标表的能力。
+### field_rules [Array<Map>]
-### row_error_handle_way.error_table [string]
+校验规则。没有非空的 `table_transform` 列表时,转换级必须配置 `field_rules`;`table_transform = []`
不能免除这个要求。
-当 `row_error_handle_way` 设置为 `ROUTE_TO_TABLE` 时,用于路由无效数据的目标表名。框架不会强制校验该参数,但如果在
`ROUTE_TO_TABLE` 模式下未配置,DataValidator 无法路由无效行,将输出警告日志并跳过这些行,因此使用
`ROUTE_TO_TABLE` 时应始终配置该参数。
+每个条目描述一个字段的规则,支持两种等价的写法:
-#### 错误表Schema
+- **嵌套**:每个字段一个条目,内含 `rules` 列表:
-当使用 `ROUTE_TO_TABLE`
模式时,DataValidator会自动创建一个具有固定schema的错误表来存储验证失败的数据。错误表包含以下字段:
+```hocon
+field_rules = [
+ {
+ field_name = "age"
+ rules = [
+ { rule_type = "NOT_NULL" },
+ { rule_type = "RANGE", min_value = "0", max_value = "150" }
+ ]
+ }
+]
+```
-| 字段名 | 数据类型 | 描述 |
-|--------|----------|------|
-| source_table_id | STRING | 源表标识符,标识数据来源的表 |
-| source_table_path | STRING | 源表路径,完整的表路径信息 |
-| original_data | STRING | 原始数据的JSON表示,包含验证失败的完整行数据 |
-| validation_errors | STRING | 验证错误详情的JSON数组,包含所有验证失败的字段和错误信息 |
-| create_time | TIMESTAMP | 验证错误的创建时间 |
+- **扁平**:每条规则一个条目,规则参数直接写在条目里。同一字段的多个扁平条目会合并为一条字段规则:
-**完整错误表记录示例**:
-```json
-{
- "source_table_id": "users_table",
- "source_table_path": "database.users",
- "original_data": "{\"id\": 123, \"name\": null, \"age\": 200, \"email\":
\"invalid-email\"}",
- "validation_errors": "[{\"field_name\": \"name\", \"error_message\": \"Field
'name' cannot be null\"}, {\"field_name\": \"age\", \"error_message\": \"Field
'age' value 200 is not within range [0, 150]\"}, {\"field_name\": \"email\",
\"error_message\": \"Field 'email' does not match pattern
'^[\\\\w-\\\\.]+@([\\\\w-]+\\\\.)+[\\\\w-]{2,4}$'\"}]",
- "create_time": "2024-01-15T10:30:45"
-}
+```hocon
+field_rules = [
+ { field_name = "age", rule_type = "NOT_NULL" },
+ { field_name = "age", rule_type = "RANGE", min_value = "0", max_value =
"150" }
+]
```
-**数据路由机制**:
-- 验证通过的数据会保持原始schema并路由到主输出表
-- 验证失败的数据会被转换为上述错误表schema格式并路由到指定的错误表
-- 每个验证失败的行都会在错误表中生成一条记录,包含完整的原始数据和详细的错误信息
+每个条目必须包含非空白的 `field_name`,且带 `rule_type` 或非空 `rules`
列表;否则任务提交时会因校验错误而失败。输入模式中不存在的字段的规则会带警告跳过,未知的规则类型也会带警告忽略。
+
+支持的规则类型:
+
+| rule_type | 参数 | 描述 |
+|-----------|------|------|
+| `NOT_NULL` | custom_message | 值为 `null` 时失败。 |
+| `RANGE` | min_value、max_value、min_inclusive、max_inclusive、custom_message |
值超出范围时失败。默认两端均为闭区间。`null` 值会通过此规则——请与 `NOT_NULL` 组合使用来拒绝空值。 |
+| `LENGTH` | min_length、max_length、exact_length、custom_message |
校验字符串、数组和集合的长度。先检查 `exact_length`,再检查 `min_length` / `max_length`。`null`
值会通过此规则。 |
+| `REGEX` | pattern(必需)、case_sensitive、custom_message | 用 Java
正则表达式匹配值。默认区分大小写。 |
+| `UDF` | function_name(必需)、custom_message | 执行内置或自定义的校验函数。内置:`EMAIL`(基于 OWASP
建议的实用邮箱校验)。 |
+
+规则参数说明:
+
+- **min_value / max_value**:两侧均为数值时按 `BigDecimal`
比较,因此字段类型不必与边界类型一致;无法解析为数字的值按其字符串表示比较。
+- **min_inclusive / max_inclusive**:默认 `true`(闭区间)。设为 `false` 则该端为开区间。
+- **min_length / max_length / exact_length**:整数。字符串长度按 Java UTF-16
代码单元计数;数组长度为元素个数(二进制数组按字节数);集合长度为其大小。
+- **case_sensitive**:默认 `true`。
+- **custom_message**:替换规则的默认错误消息。它同时出现在 `FAIL` 模式的异常消息和错误表的
`validation_errors` 列中。
+- 规则参数值可以写成数字或数字字符串(例如 `min_length = 2` 与 `min_length = "2"` 等价)。
+
+### row_error_handle_way [Enum]
+
+至少违反一条规则的行的处理方式:
+
+- `FAIL`(默认):转换抛出校验错误,作业失败。异常消息会合并该行所有失败规则的错误消息。
+- `SKIP`:丢弃无效行;有效行继续向下游传递。
+- `ROUTE_TO_TABLE`:无效行被转换为错误记录,路由到 `row_error_handle_way.error_table`
配置的错误表。未配置错误表(或值为空白)时,无效行会带警告丢弃。
+
+:::caution
+`ROUTE_TO_TABLE` 要求 sink 支持多表:转换会同时产出校验表和错误表,sink 必须能把两张表都写出去。
+:::
-### field_rules [array]
+### row_error_handle_way.error_table [String]
-字段验证规则数组。每个规则定义特定字段的验证条件。
+接收被路由无效行的表。取值为:
-单表配置必须设置 `field_rules`。使用 `table_transform` 时每个条目自己声明 `field_rules`,外层可选。
+- 不含点号(.)的纯表名——错误表与输入表放在同一个数据库/schema 中;
+- 含点号的路径(例如 `error_db.error_data` 或 `db.error_schema.error_data`)——按原样作为表路径使用。
-`table_match_regex` 选择转换级别规则适用的表(默认 `.*`),`table_transform`
保存完整的单表规则(`table_path` 加上 `field_rules`),`rule_match_mode`(`FIRST_MATCH` 或
`ALL_MATCH`)控制相同 `table_path` 条目的求值方式。参见 [多表转换](transform-multi-table.md)。
+每条被路由的行都是一条错误记录,固定模式如下:
-#### 字段规则结构
+| 列 | 类型 | 描述 |
+|----|------|------|
+| source_table_id | String |
该行来源表的完整标识符(catalog.database.schema.table,按实际存在的部分组成)。 |
+| source_table_path | String | 源表的表路径。 |
+| original_data | String | 完整原始行的 JSON 对象。 |
+| validation_errors | String | `{field_name, error_message}` 对象的 JSON
数组,每条失败规则一个。 |
+| create_time | LocalDateTime | 错误记录的产生时间。 |
-每个字段规则包含:
-- `field_name`: 要验证的字段名称
-- `rules`: 要应用的验证规则数组(嵌套格式),或单独的规则属性(扁平格式)
+### table_match_regex [String]
-#### 验证规则类型
+针对完整上游表路径匹配的 Java 正则表达式,例如 `test.abc` 或 `database.schema.table`。默认值 `.*`
匹配所有表路径。这里匹配的是实际表路径,不是 `plugin_input` 或 `plugin_output` 中的数据集名称。
-##### NOT_NULL
-验证字段值不为空。
+此选项为转换级规则选择表,不限制显式的 `table_transform` 条目。
-参数:
-- `rule_type`: "NOT_NULL"
-- `custom_message` (可选): 自定义错误消息
+### table_transform [Array<Map>]
-##### RANGE
-验证数值在指定范围内。
+表级规则列表,默认为空列表。每个条目必须包含非空白的 `table_path`(精确路径,不是正则表达式),格式为
`databaseName[.schemaName].tableName`,外加该表一条完整的单表 DataValidator
规则:`field_rules` 和可选的错误处理策略。
-参数:
-- `rule_type`: "RANGE"
-- `min_value` (可选): 最小允许值
-- `max_value` (可选): 最大允许值
-- `min_inclusive` (可选): 最小值是否包含在内(默认: true)
-- `max_inclusive` (可选): 最大值是否包含在内(默认: true)
-- `custom_message` (可选): 自定义错误消息
+条目声明自己的 `field_rules`,不继承转换级的 `field_rules`。即使该表不匹配
`table_match_regex`,匹配的条目也优先。错误处理策略是例外:见下文"多表配置"。
-##### LENGTH
-验证字符串、数组或集合值的长度。
+### rule_match_mode [Enum]
-数组长度为元素个数,包含空元素。嵌套数组只计算最外层的长度,二进制值按字节数计算。
-字符串长度使用 Java UTF-16 代码单元数,集合长度使用集合大小。
-空值通过此规则;如需拒绝空值,请组合使用 `NOT_NULL`。
+控制多个条目具有相同精确 `table_path` 时的行为:
-参数:
-- `rule_type`: "LENGTH"
-- `min_length` (可选): 最小允许长度
-- `max_length` (可选): 最大允许长度
-- `exact_length` (可选): 精确要求的长度
-- `custom_message` (可选): 自定义错误消息
+- 显式设置 `FIRST_MATCH`:按列表顺序使用第一条匹配的条目。
+- 显式设置 `ALL_MATCH`:按列表顺序执行所有匹配的条目;同一表中靠前条目的输出成为下一个匹配条目的输入。
-##### REGEX
-验证字符串值匹配正则表达式模式。
+虽然选项的默认值为 `FIRST_MATCH`,但省略此选项时,重复的 `table_path`
条目会在转换初始化阶段被拒绝。如果确实需要重复路径,请显式设置此选项。路径不重复时,使用默认值即可。
-参数:
-- `rule_type`: "REGEX"
-- `pattern`: 正则表达式模式(必需)
-- `case_sensitive` (可选): 模式匹配是否区分大小写(默认: true)
-- `custom_message` (可选): 自定义错误消息
+### common options
-##### UDF (用户自定义函数)
-使用自定义业务逻辑实现的用户自定义函数验证字段值。
+使用 `plugin_input` 和 `plugin_output`
连接上游和下游插件。通用参数详见[转换插件](common-options/common-options.md)。
-参数:
-- `rule_type`: "UDF"
-- `function_name`: 要执行的UDF函数名称(必需)
-- `custom_message` (可选): 自定义错误消息
+## 多表配置
-**内置UDF函数:**
-- `EMAIL`: 基于OWASP建议使用实用验证规则验证电子邮件地址
+对于每个输入表,按照以下顺序选择有效规则:
-**创建自定义UDF函数:**
-要创建自定义UDF函数:
-1. 实现 `DataValidatorUDF` 接口
-2. 使用 `@AutoService(DataValidatorUDF.class)` 注解
-3. 提供唯一的 `functionName()`
-4. 实现包含自定义逻辑的 `validate()` 方法
+1. 根据 `rule_match_mode` 使用匹配的一个或多个 `table_transform` 条目。
+2. 否则,配置了转换级规则(见 `field_rules`)且表路径匹配 `table_match_regex` 时,使用转换级规则。
+3. 否则,原样传递该表的行。
-### 通用选项 [string]
+仅配置 `table_transform` 时,未列出的表原样传递。`field_rules`
的存在标志着转换级规则已配置:没有它,其余转换级选项对字段规则不产生作用。
-转换插件通用参数,请参考 [Transform Plugin](common-options/common-options.md) 了解详情
+DataValidator 有一个行为不同的选项组:`row_error_handle_way` 和
`row_error_handle_way.error_table` 是错误处理**策略**,在转换级配置一次,同时也作用于
`table_transform` 条目选择的表,除非条目自行设置。这样一张错误表就能服务于所有被校验的表。
+
+下面的示例涵盖全部三种配置方式。共享的匹配规则详见[多表转换](transform-multi-table.md)。
## 示例
-### 示例 1: 使用 FAIL 模式的基本验证
+以下完整批处理配置使用 FakeSource 和 Console。在 SeaTunnel 发行包中安装这两个连接器后,可以将配置保存为文件,并通过
`bin/seatunnel.sh --config <file> -e local` 运行。行数由 FakeSource 的 `rows`
选项固定,因此预期输出是确定的。
+
+### 仅使用转换级规则,配合 ROUTE_TO_TABLE
+
+输入共六行,其中三行违反规则(`name` 为 null、age 为 200、邮箱格式错误)。配置 `ROUTE_TO_TABLE`
后,有效行继续流向校验输出,每条无效行则被转换为错误记录并路由到 `error_data`:
```hocon
+env {
+ job.mode = "BATCH"
+ parallelism = 1
+}
+
+source {
+ FakeSource {
+ plugin_output = "fake"
+ schema {
+ fields {
+ id = "int"
+ name = "string"
+ age = "int"
+ email = "string"
+ }
+ }
+ rows = [
+ { fields = [1, "John Doe", 25, "[email protected]"], kind = INSERT }
+ { fields = [2, "Jane Smith", 30, "[email protected]"], kind = INSERT }
+ { fields = [3, "Charlie Wilson", 32, "[email protected]"], kind =
INSERT }
+ { fields = [4, null, 30, "[email protected]"], kind = INSERT }
+ { fields = [5, "Bob Johnson", 200, "[email protected]"], kind = INSERT }
+ { fields = [6, "Alice Brown", 28, "invalid-email"], kind = INSERT }
+ ]
+ }
+}
+
transform {
DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "FAIL"
+ plugin_input = "fake"
+ plugin_output = "validated"
+ row_error_handle_way = "ROUTE_TO_TABLE"
+ row_error_handle_way.error_table = "error_data"
field_rules = [
{
field_name = "name"
rule_type = "NOT_NULL"
+ custom_message = "name must not be null"
},
{
field_name = "age"
rule_type = "RANGE"
- min_value = 0
- max_value = 150
+ min_value = "0"
+ max_value = "150"
},
{
field_name = "email"
rule_type = "REGEX"
pattern = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"
+ custom_message = "invalid email format"
}
]
}
}
+
+sink {
+ Console {
+ plugin_input = "validated"
+ }
+}
```
-### 示例 2: 使用 SKIP 模式的验证
+`validated` 输出保留第 1–3 行不变。`error_data` 表接收三条错误记录;例如第 5 行的记录为:
+
+| source_table_id | source_table_path | original_data | validation_errors |
create_time |
+|-----------------|-------------------|---------------|-------------------|-------------|
+| ... | fake | {"id":5,"name":"Bob
Johnson","age":200,"email":"[email protected]"} |
[{"field_name":"age","error_message":"Value 200 exceeds maximum 150"}] | ... |
+
+第 6 行的记录在 `validation_errors` 中为
`[{"field_name":"email","error_message":"invalid email format"}]`,因为规则的
`custom_message` 替换了默认消息。
+
+:::tip
+配置 `row_error_handle_way = "FAIL"`(默认)时,同一配置在遇到第一条无效行时就会使作业失败;配置 `SKIP`
时三条无效行会被静默丢弃,只有第 1–3 行到达 sink。
+:::
+
+### 转换级规则与表级规则组合
+
+每个输入表各含两行有效数据。`test.abc` 由转换级 `field_rules` 校验,`test.xyz` 使用自己的
`table_transform` 条目。错误处理策略(`FAIL`)在转换级设置一次,对两张表都生效。
+
+| 表 | 有效字段规则 | 输出行数 |
+|----|--------------|----------|
+| `test.abc` | 转换级:`name` NOT_NULL,`age` RANGE 0–150。 | 2 |
+| `test.xyz` | 表级条目:`name` NOT_NULL,`email` REGEX。 | 2 |
```hocon
-transform {
- DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "SKIP"
- field_rules = [
+env {
+ job.mode = "BATCH"
+ parallelism = 1
+}
+
+source {
+ FakeSource {
+ plugin_output = "fake"
+ tables_configs = [
{
- field_name = "name"
- rule_type = "NOT_NULL"
+ schema {
+ table = "test.abc"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "John Doe", 25, "[email protected]"], kind = INSERT }
+ { fields = [2, "Jane Smith", 30, "[email protected]"], kind = INSERT }
+ ]
},
{
- field_name = "name"
- rule_type = "LENGTH"
- min_length = 2
- max_length = 50
+ schema {
+ table = "test.xyz"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "Bob Johnson", 35, "[email protected]"], kind = INSERT
}
+ { fields = [2, "Alice Brown", 28, "[email protected]"], kind =
INSERT }
+ ]
}
]
}
}
-```
-
-### 示例 3: 使用 ROUTE_TO_TABLE 模式的验证
-```hocon
transform {
DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "ROUTE_TO_TABLE"
- row_error_handle_way.error_table = "error_data"
+ plugin_input = "fake"
+ plugin_output = "validated"
+ row_error_handle_way = "FAIL"
+ // 应用于所有未被 table_transform 条目覆盖的表。
field_rules = [
{
field_name = "name"
@@ -209,135 +292,160 @@ transform {
{
field_name = "age"
rule_type = "RANGE"
- min_value = 0
- max_value = 150
+ min_value = "0"
+ max_value = "150"
}
]
- }
-}
-```
-
-**注意**: 使用 `ROUTE_TO_TABLE` 时,请确保您的 sink 连接器支持多表。有效数据将发送到主输出表,而无效数据将路由到指定的错误表。
-
-在此示例中:
-- 验证通过的数据将保持原始schema(包含name、age等字段)并发送到主输出表
--
验证失败的数据将被转换为错误表schema(包含source_table_id、source_table_path、original_data、validation_errors、create_time字段)并路由到"error_data"表
-### 示例 4: 嵌套规则格式
-
-```hocon
-transform {
- DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
- row_error_handle_way = "FAIL"
- field_rules = [
+ table_transform = [
{
- field_name = "name"
- rules = [
+ table_path = "test.xyz"
+ field_rules = [
{
+ field_name = "name"
rule_type = "NOT_NULL"
- custom_message = "姓名是必需的"
},
{
- rule_type = "LENGTH"
- min_length = 2
- max_length = 50
- custom_message = "姓名长度必须在2到50个字符之间"
+ field_name = "email"
+ rule_type = "REGEX"
+ pattern = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"
}
]
}
]
}
}
+
+sink {
+ Console {
+ plugin_input = "validated"
+ }
+}
```
-### 示例 5: 使用内置UDF进行邮箱验证
+### 仅使用表级规则
+
+没有转换级 `field_rules`:每张表都由自己的 `table_transform`
条目校验,其他任何表都将原样传递。错误处理策略仍在转换级配置,作用于所有被校验的表。
```hocon
+env {
+ job.mode = "BATCH"
+ parallelism = 1
+}
+
+source {
+ FakeSource {
+ plugin_output = "fake"
+ tables_configs = [
+ {
+ schema {
+ table = "test.abc"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "John Doe", 25, "[email protected]"], kind = INSERT }
+ { fields = [2, "Jane Smith", 30, "[email protected]"], kind = INSERT }
+ ]
+ },
+ {
+ schema {
+ table = "test.xyz"
+ columns = [
+ { name = "id", type = "int" },
+ { name = "name", type = "string" },
+ { name = "age", type = "int" },
+ { name = "email", type = "string" }
+ ]
+ }
+ rows = [
+ { fields = [1, "Bob Johnson", 35, "[email protected]"], kind = INSERT
}
+ { fields = [2, "Alice Brown", 28, "[email protected]"], kind =
INSERT }
+ ]
+ }
+ ]
+ }
+}
+
transform {
DataValidator {
- plugin_input = "source_table"
- plugin_output = "validated_table"
+ plugin_input = "fake"
+ plugin_output = "validated"
row_error_handle_way = "FAIL"
- field_rules = [
+ table_transform = [
{
- field_name = "email"
- rule_type = "UDF"
- function_name = "EMAIL"
- custom_message = "邮箱地址格式无效"
+ table_path = "test.abc"
+ field_rules = [
+ {
+ field_name = "name"
+ rule_type = "NOT_NULL"
+ },
+ {
+ field_name = "age"
+ rule_type = "RANGE"
+ min_value = "0"
+ max_value = "150"
+ }
+ ]
+ },
+ {
+ table_path = "test.xyz"
+ field_rules = [
+ {
+ field_name = "name"
+ rule_type = "NOT_NULL"
+ },
+ {
+ field_name = "email"
+ rule_type = "REGEX"
+ pattern = "^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$"
+ }
+ ]
}
]
}
}
+
+sink {
+ Console {
+ plugin_input = "validated"
+ }
+}
```
-## UDF开发指南
+此输入中两张表都有效,因此四行全部通过校验。若 `test.abc` 出现无效行,作业将失败,因为转换级 `row_error_handle_way =
"FAIL"` 策略在没有转换级 `field_rules` 时依然生效;没有条目的表则不经校验直接通过。
-### 创建自定义UDF函数
+## 开发自定义 UDF 规则
-要创建自定义验证UDF函数,请按照以下步骤:
+除内置的 `EMAIL` 函数外,你还可以添加自己的校验函数:
-#### 1. 实现DataValidatorUDF接口
+1. 实现 `DataValidatorUDF`
接口(`org.apache.seatunnel.transform.validator.udf.DataValidatorUDF`),返回唯一的
`functionName()` 和 `validate()` 逻辑:
```java
-package com.example.validator;
-
-import org.apache.seatunnel.api.table.type.SeaTunnelDataType;
-import org.apache.seatunnel.transform.validator.ValidationContext;
-import org.apache.seatunnel.transform.validator.ValidationResult;
-import org.apache.seatunnel.transform.validator.udf.DataValidatorUDF;
-import com.google.auto.service.AutoService;
-
@AutoService(DataValidatorUDF.class)
public class PhoneValidator implements DataValidatorUDF {
@Override
public String functionName() {
- return "PHONE_VALIDATOR";
+ return "PHONE";
}
@Override
public ValidationResult validate(
Object value, SeaTunnelDataType<?> dataType, ValidationContext
context) {
-
if (value == null) {
return ValidationResult.success();
}
-
- String phone = value.toString().trim();
-
- // 自定义手机号验证逻辑
- if (phone.matches("^\\+?[1-9]\\d{1,14}$")) {
- return ValidationResult.success();
- } else {
- return ValidationResult.failure("手机号码格式无效: " + phone);
- }
- }
-
- @Override
- public String getDescription() {
- return "验证国际手机号码格式";
+ return value.toString().trim().matches("^\\+?[1-9]\\d{1,14}$")
+ ? ValidationResult.success()
+ : ValidationResult.failure("Invalid phone number format: " +
value);
}
}
```
-#### 2. 注册UDF
-
-UDF通过 `@AutoService(DataValidatorUDF.class)`
注解自动注册。这使用Java的ServiceLoader机制在运行时发现和加载UDF实现。
-
-#### 3. 打包和部署
-
-1. 编译您的UDF类并将其打包到JAR文件中
-2. 将JAR文件放置在SeaTunnel类路径中
-3. UDF将被自动发现并可供使用
-
-**使用示例**:
-```hocon
-{
- field_name = "email"
- rule_type = "UDF"
- function_name = "EMAIL"
- custom_message = "请提供有效的邮箱地址"
-}
-```
+2. 使用 `@AutoService(DataValidatorUDF.class)` 注解该类,使其被 Java 的 `ServiceLoader`
机制发现。
+3. 把编译好的类打包为 JAR 并放入 SeaTunnel 类路径;之后该函数即可通过其 `function_name` 使用。