FileSystem SQL Connector

This connector provides access to partitioned files in filesystems supported by the Flink FileSystem abstraction.

The file system connector itself is included in Flink and does not require an additional dependency. A corresponding format needs to be specified for reading and writing rows from and to a file system.

The file system connector allows for reading and writing from a local or distributed filesystem. A filesystem table can be defined as:

  1. CREATE TABLE MyUserTable (
  2. column_name1 INT,
  3. column_name2 STRING,
  4. ...
  5. part_name1 INT,
  6. part_name2 STRING
  7. ) PARTITIONED BY (part_name1, part_name2) WITH (
  8. 'connector' = 'filesystem', -- required: specify the connector
  9. 'path' = 'file:///path/to/whatever', -- required: path to a directory
  10. 'format' = '...', -- required: file system connector requires to specify a format,
  11. -- Please refer to Table Formats
  12. -- section for more details
  13. 'partition.default-name' = '...', -- optional: default partition name in case the dynamic partition
  14. -- column value is null/empty string
  15. -- optional: the option to enable shuffle data by dynamic partition fields in sink phase, this can greatly
  16. -- reduce the number of file for filesystem sink but may lead data skew, the default value is false.
  17. 'sink.shuffle-by-partition.enable' = '...',
  18. ...
  19. )

Make sure to include Flink File System specific dependencies.

File system sources for streaming is still under development. In the future, the community will add support for common streaming use cases, i.e., partition and directory monitoring.

The behaviour of file system connector is much different from previous legacy filesystem connector: the path parameter is specified for a directory not for a file and you can’t get a human-readable file in the path that you declare.

Partition Files

Flink’s file system partition support uses the standard hive format. However, it does not require partitions to be pre-registered with a table catalog. Partitions are discovered and inferred based on directory structure. For example, a table partitioned based on the directory below would be inferred to contain datetime and hour partitions.

  1. path
  2. └── datetime=2019-08-25
  3. └── hour=11
  4. ├── part-0.parquet
  5. ├── part-1.parquet
  6. └── hour=12
  7. ├── part-0.parquet
  8. └── datetime=2019-08-26
  9. └── hour=6
  10. ├── part-0.parquet

The file system table supports both partition inserting and overwrite inserting. See INSERT Statement. When you insert overwrite to a partitioned table, only the corresponding partition will be overwritten, not the entire table.

File Formats

The file system connector supports multiple formats:

Streaming Sink

The file system connector supports streaming writes, based on Flink’s Streaming File Sink to write records to file. Row-encoded Formats are csv and json. Bulk-encoded Formats are parquet, orc and avro.

You can write SQL directly, insert the stream data into the non-partitioned table. If it is a partitioned table, you can configure partition related operations. See Partition Commit for details.

Rolling Policy

Data within the partition directories are split into part files. Each partition will contain at least one part file for each subtask of the sink that has received data for that partition. The in-progress part file will be closed and additional part file will be created according to the configurable rolling policy. The policy rolls part files based on size, a timeout that specifies the maximum duration for which a file can be open.

KeyDefaultTypeDescription
sink.rolling-policy.file-size
128MBMemorySizeThe maximum part file size before rolling.
sink.rolling-policy.rollover-interval
30 minDurationThe maximum time duration a part file can stay open before rolling (by default 30 min to avoid to many small files). The frequency at which this is checked is controlled by the ‘sink.rolling-policy.check-interval’ option.
sink.rolling-policy.check-interval
1 minDurationThe interval for checking time based rolling policies. This controls the frequency to check whether a part file should rollover based on ‘sink.rolling-policy.rollover-interval’.

NOTE: For bulk formats (parquet, orc, avro), the rolling policy in combination with the checkpoint interval(pending files become finished on the next checkpoint) control the size and number of these parts.

NOTE: For row formats (csv, json), you can set the parameter sink.rolling-policy.file-size or sink.rolling-policy.rollover-interval in the connector properties and parameter execution.checkpointing.interval in flink-conf.yaml together if you don’t want to wait a long period before observe the data exists in file system. For other formats (avro, orc), you can just set parameter execution.checkpointing.interval in flink-conf.yaml.

File Compaction

The file sink supports file compactions, which allows applications to have smaller checkpoint intervals without generating a large number of files.

KeyDefaultTypeDescription
auto-compaction
falseBooleanWhether to enable automatic compaction in streaming sink or not. The data will be written to temporary files. After the checkpoint is completed, the temporary files generated by a checkpoint will be compacted. The temporary files are invisible before compaction.
compaction.file-size
(none)MemorySizeThe compaction target file size, the default value is the rolling file size.

If enabled, file compaction will merge multiple small files into larger files based on the target file size. When running file compaction in production, please be aware that:

  • Only files in a single checkpoint are compacted, that is, at least the same number of files as the number of checkpoints is generated.
  • The file before merging is invisible, so the visibility of the file may be: checkpoint interval + compaction time.
  • If the compaction takes too long, it will backpressure the job and extend the time period of checkpoint.

Partition Commit

After writing a partition, it is often necessary to notify downstream applications. For example, add the partition to a Hive metastore or writing a _SUCCESS file in the directory. The file system sink contains a partition commit feature that allows configuring custom policies. Commit actions are based on a combination of triggers and policies.

  • Trigger: The timing of the commit of the partition can be determined by the watermark with the time extracted from the partition, or by processing time.
  • Policy: How to commit a partition, built-in policies support for the commit of success files and metastore, you can also implement your own policies, such as triggering hive’s analysis to generate statistics, or merging small files, etc.

NOTE: Partition Commit only works in dynamic partition inserting.

Partition commit trigger

To define when to commit a partition, providing partition commit trigger:

KeyDefaultTypeDescription
sink.partition-commit.trigger
process-timeStringTrigger type for partition commit: ‘process-time’: based on the time of the machine, it neither requires partition time extraction nor watermark generation. Commit partition once the ‘current system time’ passes ‘partition creation system time’ plus ‘delay’. ‘partition-time’: based on the time that extracted from partition values, it requires watermark generation. Commit partition once the ‘watermark’ passes ‘time extracted from partition values’ plus ‘delay’.
sink.partition-commit.delay
0 sDurationThe partition will not commit until the delay time. If it is a daily partition, should be ‘1 d’, if it is a hourly partition, should be ‘1 h’.
sink.partition-commit.watermark-time-zone
UTCStringThe time zone to parse the long watermark value to TIMESTAMP value, the parsed watermark timestamp is used to compare with partition time to decide the partition should commit or not. This option is only take effect when sink.partition-commit.trigger is set to ‘partition-time’. If this option is not configured correctly, e.g. source rowtime is defined on TIMESTAMP_LTZ column, but this config is not configured, then users may see the partition committed after a few hours. The default value is ‘UTC’, which means the watermark is defined on TIMESTAMP column or not defined. If the watermark is defined on TIMESTAMP_LTZ column, the time zone of watermark is the session time zone. The option value is either a full name such as ‘America/Los_Angeles’, or a custom timezone id such as ‘GMT-8:00’.

There are two types of trigger:

  • The first is partition processing time. It neither requires partition time extraction nor watermark generation. The trigger of partition commit according to partition creation time and current system time. This trigger is more universal, but not so precise. For example, data delay or failover will lead to premature partition commit.
  • The second is the trigger of partition commit according to the time that extracted from partition values and watermark. This requires that your job has watermark generation, and the partition is divided according to time, such as hourly partition or daily partition.

If you want to let downstream see the partition as soon as possible, no matter whether its data is complete or not:

  • ‘sink.partition-commit.trigger’=‘process-time’ (Default value)
  • ‘sink.partition-commit.delay’=‘0s’ (Default value) Once there is data in the partition, it will immediately commit. Note: the partition may be committed multiple times.

If you want to let downstream see the partition only when its data is complete, and your job has watermark generation, and you can extract the time from partition values:

  • ‘sink.partition-commit.trigger’=‘partition-time’
  • ‘sink.partition-commit.delay’=‘1h’ (‘1h’ if your partition is hourly partition, depends on your partition type) This is the most accurate way to commit partition, and it will try to ensure that the committed partitions are as data complete as possible.

If you want to let downstream see the partition only when its data is complete, but there is no watermark, or the time cannot be extracted from partition values:

  • ‘sink.partition-commit.trigger’=‘process-time’ (Default value)
  • ‘sink.partition-commit.delay’=‘1h’ (‘1h’ if your partition is hourly partition, depends on your partition type) Try to commit partition accurately, but data delay or failover will lead to premature partition commit.

Late data processing: The record will be written into its partition when a record is supposed to be written into a partition that has already been committed, and then the committing of this partition will be triggered again.

Partition Time Extractor

Time extractors define extracting time from partition values.

KeyDefaultTypeDescription
partition.time-extractor.kind
defaultStringTime extractor to extract time from partition values. Support default and custom. For default, can configure timestamp pattern. For custom, should configure extractor class.
partition.time-extractor.class
(none)StringThe extractor class for implement PartitionTimeExtractor interface.
partition.time-extractor.timestamp-pattern
(none)StringThe ‘default’ construction way allows users to use partition fields to get a legal timestamp pattern. Default support ‘yyyy-mm-dd hh:mm:ss’ from first field. If timestamp should be extracted from a single partition field ‘dt’, can configure: ‘$dt’. If timestamp should be extracted from multiple partition fields, say ‘year’, ‘month’, ‘day’ and ‘hour’, can configure: ‘$year-$month-$day $hour:00:00’. If timestamp should be extracted from two partition fields ‘dt’ and ‘hour’, can configure: ‘$dt $hour:00:00’.

The default extractor is based on a timestamp pattern composed of your partition fields. You can also specify an implementation for fully custom partition extraction based on the PartitionTimeExtractor interface.

  1. public class HourPartTimeExtractor implements PartitionTimeExtractor {
  2. @Override
  3. public LocalDateTime extract(List<String> keys, List<String> values) {
  4. String dt = values.get(0);
  5. String hour = values.get(1);
  6. return Timestamp.valueOf(dt + " " + hour + ":00:00").toLocalDateTime();
  7. }
  8. }

Partition Commit Policy

The partition commit policy defines what action is taken when partitions are committed.

  • The first is metastore, only hive table supports metastore policy, file system manages partitions through directory structure.
  • The second is the success file, which will write an empty file in the directory corresponding to the partition.
KeyDefaultTypeDescription
sink.partition-commit.policy.kind
(none)StringPolicy to commit a partition is to notify the downstream application that the partition has finished writing, the partition is ready to be read. metastore: add partition to metastore. Only hive table supports metastore policy, file system manages partitions through directory structure. success-file: add ‘_success’ file to directory. Both can be configured at the same time: ‘metastore,success-file’. custom: use policy class to create a commit policy. Support to configure multiple policies: ‘metastore,success-file’.
sink.partition-commit.policy.class
(none)StringThe partition commit policy class for implement PartitionCommitPolicy interface. Only work in custom commit policy.
sink.partition-commit.success-file.name
_SUCCESSStringThe file name for success-file partition commit policy, default is ‘_SUCCESS’.

You can extend the implementation of commit policy, The custom commit policy implementation like:

  1. public class AnalysisCommitPolicy implements PartitionCommitPolicy {
  2. private HiveShell hiveShell;
  3. @Override
  4. public void commit(Context context) throws Exception {
  5. if (hiveShell == null) {
  6. hiveShell = createHiveShell(context.catalogName());
  7. }
  8. hiveShell.execute(String.format(
  9. "ALTER TABLE %s ADD IF NOT EXISTS PARTITION (%s = '%s') location '%s'",
  10. context.tableName(),
  11. context.partitionKeys().get(0),
  12. context.partitionValues().get(0),
  13. context.partitionPath()));
  14. hiveShell.execute(String.format(
  15. "ANALYZE TABLE %s PARTITION (%s = '%s') COMPUTE STATISTICS FOR COLUMNS",
  16. context.tableName(),
  17. context.partitionKeys().get(0),
  18. context.partitionValues().get(0)));
  19. }
  20. }

Sink Parallelism

The parallelism of writing files into external file system (including Hive) can be configured by the corresponding table option, which is supported both in streaming mode and in batch mode. By default, the parallelism is configured to being the same as the parallelism of its last upstream chained operator. When the parallelism which is different from the parallelism of the upstream parallelism is configured, the operator of writing files and the operator compacting files (if used) will apply the parallelism.

KeyDefaultTypeDescription
sink.parallelism
(none)IntegerParallelism of writing files into external file system. The value should greater than zero otherwise exception will be thrown.

NOTE: Currently, Configuring sink parallelism is supported if and only if the changelog mode of upstream is INSERT-ONLY. Otherwise, exception will be thrown.

Full Example

The below examples show how the file system connector can be used to write a streaming query to write data from Kafka into a file system and runs a batch query to read that data back out.

  1. CREATE TABLE kafka_table (
  2. user_id STRING,
  3. order_amount DOUBLE,
  4. log_ts TIMESTAMP(3),
  5. WATERMARK FOR log_ts AS log_ts - INTERVAL '5' SECOND
  6. ) WITH (...);
  7. CREATE TABLE fs_table (
  8. user_id STRING,
  9. order_amount DOUBLE,
  10. dt STRING,
  11. `hour` STRING
  12. ) PARTITIONED BY (dt, `hour`) WITH (
  13. 'connector'='filesystem',
  14. 'path'='...',
  15. 'format'='parquet',
  16. 'sink.partition-commit.delay'='1 h',
  17. 'sink.partition-commit.policy.kind'='success-file'
  18. );
  19. -- streaming sql, insert into file system table
  20. INSERT INTO fs_table
  21. SELECT
  22. user_id,
  23. order_amount,
  24. DATE_FORMAT(log_ts, 'yyyy-MM-dd'),
  25. DATE_FORMAT(log_ts, 'HH')
  26. FROM kafka_table;
  27. -- batch sql, select with partition pruning
  28. SELECT * FROM fs_table WHERE dt='2020-05-20' and `hour`='12';

If the watermark is defined on TIMESTAMP_LTZ column and used partition-time to commit, the sink.partition-commit.watermark-time-zone is required to set to the session time zone, otherwise the partition committed may happen after a few hours.

  1. CREATE TABLE kafka_table (
  2. user_id STRING,
  3. order_amount DOUBLE,
  4. ts BIGINT, -- time in epoch milliseconds
  5. ts_ltz AS TO_TIMESTAMP_LTZ(ts, 3),
  6. WATERMARK FOR ts_ltz AS ts_ltz - INTERVAL '5' SECOND -- Define watermark on TIMESTAMP_LTZ column
  7. ) WITH (...);
  8. CREATE TABLE fs_table (
  9. user_id STRING,
  10. order_amount DOUBLE,
  11. dt STRING,
  12. `hour` STRING
  13. ) PARTITIONED BY (dt, `hour`) WITH (
  14. 'connector'='filesystem',
  15. 'path'='...',
  16. 'format'='parquet',
  17. 'partition.time-extractor.timestamp-pattern'='$dt $hour:00:00',
  18. 'sink.partition-commit.delay'='1 h',
  19. 'sink.partition-commit.trigger'='partition-time',
  20. 'sink.partition-commit.watermark-time-zone'='Asia/Shanghai', -- Assume user configured time zone is 'Asia/Shanghai'
  21. 'sink.partition-commit.policy.kind'='success-file'
  22. );
  23. -- streaming sql, insert into file system table
  24. INSERT INTO fs_table
  25. SELECT
  26. user_id,
  27. order_amount,
  28. DATE_FORMAT(ts_ltz, 'yyyy-MM-dd'),
  29. DATE_FORMAT(ts_ltz, 'HH')
  30. FROM kafka_table;
  31. -- batch sql, select with partition pruning
  32. SELECT * FROM fs_table WHERE dt='2020-05-20' and `hour`='12';