说明
Template 格式允许用户通过值占位符指定自定义的格式字符串,
并为数据指定转义规则。
它使用以下设置:
设置与转义规则
format_template_row
format_template_row 用于指定包含行格式字符串的文件路径,语法如下:
支持以下转义规则:
如果省略转义规则,则使用
None。XML 仅适用于输出。SELECT) 或作为预期输入 (如果使用 INPUT) ,
分别位于列 Search phrase:、, count:、, ad price: $ 与 ; 分隔符之间:
s(转义规则为Quoted)c(转义规则为Escaped)p(转义规则为JSON)
- 如果执行
INSERT,下面这一行符合预期模板,并会将值bathroom interior design、2166、$3读入列Search phrase、count、ad price。 - 如果执行
SELECT,则下面这一行就是输出结果,前提是值bathroom interior design、2166、$3已经存储在某个表的列Search phrase、count、ad price中。
format_template_rows_between_delimiter
format_template_rows_between_delimiter 用于指定行与行之间的分隔符;除最后一行外,它会在每一行后输出 (或期望存在) 该分隔符 (默认为 \n)
format_template_resultset
format_template_resultset 用于指定一个文件路径,该文件包含结果集的格式字符串。
结果集的格式字符串与行的格式字符串语法相同。
它支持指定前缀、后缀以及输出某些附加信息的方式,并使用以下占位符来代替列名:
data表示采用format_template_row格式的数据行,并由format_template_rows_between_delimiter分隔。此占位符必须是格式字符串中的第一个占位符。totals表示采用format_template_row格式的总计值行 (使用 WITH TOTALS 时) 。min表示采用format_template_row格式的最小值行 (当 extremes 设置为 1 时) 。max表示采用format_template_row格式的最大值行 (当 extremes 设置为 1 时) 。rows表示输出的总行数。rows_before_limit表示如果没有 LIMIT,本应输出的最小行数。仅当查询包含 LIMIT 时才会输出。如果查询包含 GROUP BY,则 rows_before_limit_at_least 表示如果没有 LIMIT,本应输出的精确行数。time表示请求执行时间 (以秒为单位) 。rows_read表示已读取的行数。bytes_read表示已读取的字节数 (未压缩) 。
data、totals、min 和 max 不得指定转义规则 (或者必须显式指定 None) 。其余占位符可以指定任意转义规则。
如果
format_template_resultset 设置为空字符串,则默认值为 ${data}。内联指定
format_template_row、format_template_resultset 设置) 部署到 cluster 中所有节点上的某个 directory,会很困难,甚至根本无法实现。
此外,format 本身可能非常简单,简单到无需放在 file 中。
在这种情况下,可以使用 format_template_row_format (用于 format_template_row) 和 format_template_resultset_format (用于 format_template_resultset) ,直接在查询中设置模板字符串,
而不是将其指定为包含该字符串的 file path。
格式字符串 和转义序列的规则与以下内容相同:
- 使用
format_template_row_format时,与format_template_row的规则相同。 - 使用
format_template_resultset_format时,与format_template_resultset的规则相同。
示例用法
Template 格式的使用示例:先看如何查询数据,再看如何插入数据。
查询数据
Query
/some/path/resultset.format
/some/path/row.format
Response
插入数据
/some/path/resultset.format
/some/path/row.format
PageViews、UserID、Duration 和 Sign 都是表中的列名。每行中 Useless field 之后的值,以及后缀中 \nTotal rows: 之后的值都会被忽略。
输入数据中的所有分隔符都必须与指定格式字符串中的分隔符完全一致。
内联指定
Template 格式和内联指定设置完成一个简单任务——从 system.formats 表中 SELECT 一些 ClickHouse 格式的名称,并将其格式化为 markdown 表格。使用 Template 格式以及 format_template_row_format 和 format_template_resultset_format 设置,即可轻松实现这一点。
在前面的示例中,我们分别在单独的文件中指定了 result-set 和行的格式字符串,并通过 format_template_resultset 和 format_template_row 设置分别指定这些文件的路径。这里我们将以内联方式完成,因为我们的模板非常简单,只需要少量 | 和 - 就能构造出 markdown 表格。我们将使用 format_template_resultset_format 设置来指定 result-set 模板字符串。为了生成表头,我们在 ${data} 之前添加了 |ClickHouse Formats|\n|---|\n。我们使用 format_template_row_format 设置为各行指定模板字符串 |`{0:XML}`|。Template 格式会将按给定格式生成的各行插入到 ${data} 占位符中。在这个示例中,我们只有一列;但如果你想添加更多列,也可以在行模板字符串中加入 {1:XML}、{2:XML} 等,并根据需要选择合适的转义规则。本示例中使用的是 XML 转义规则。
Query
| 和 - 来生成 markdown 表格的麻烦:
Response