PostgreSQL码农集散地

DuckDB厉害了, csv解析玩得真6

文中参考文档在github需点击阅读原文打开, 同时推荐2个学习环境: 

1、懒人Docker镜像, 已打包200+插件:《最好的PostgreSQL学习镜像》

2、有web浏览器就能用的云起实验室: 《免费体验PolarDB开源数据库》
3、PolarDB开源数据库内核、最佳实践等学习图谱:  https://www.aliyun.com/database/openpolardb/activity 
关注公众号, 持续发布PostgreSQL、PolarDB、DuckDB等相关文章. 

DuckDB解析csv有妙招

开源技术沙龙杭州站预告:

「杭州*康恩贝」4月26日PolarDB开源数据库沙龙,开启报名!

如果要把csv导入数据库, 需要先解析csv内容的元数据格式, 例如是否有列名, 每列什么类型, 分隔符是什么, 换行符是什么, quote是啥,逃逸字符是什么等等.

DuckDB的csv解析做得比较丝滑, 可以配置采样条数, 并自动解析出元数据的内容. 使用DuckDB read_csv时我们几乎不需要手工填写任何csv元数据信息.

https://duckdb.org/docs/data/csv/auto_detection

同时DuckDB也提供了csv文件的解析函数sniff_csv, 配置采样条数, 自动解析出元数据的内容.

1、sniff_csv Function

It is possible to run the CSV sniffer as a separate step using the sniff_csv(filename) function, which returns the detected CSV properties as a table with a single row. The sniff_csv function accepts an optional sample_size parameter to configure the number of rows sampled.

FROM sniff_csv('my_file.csv');  
FROM sniff_csv('my_file.csv', sample_size = 1000);

返回元数据

Column nameDescriptionExample
Delimiterdelimiter,
Quotequote character"
Escapeescape\
NewLineDelimiternew-line delimiter\r\n
SkipRownumber of rows skipped1
HasHeaderwhether the CSV has a headertrue
Columnscolumn types encoded as a LIST of STRUCTs({'name': 'VARCHAR', 'age': 'BIGINT'})
DateFormatdate Format%d/%m/%Y
TimestampFormattimestamp Format%Y-%m-%dT%H:%M:%S.%f
UserArgumentsarguments used to invoke sniff_csvsample_size = 1000
Promptprompt ready to be used to read the CSVFROM read_csv('my_file.csv', auto_detect=false, delim=',', ...)

2、Prompt, 返回元数据提示

The Prompt column contains a SQL command with the configurations detected by the sniffer.

-- use line mode in CLI to get the full command  
.mode line
SELECT Prompt FROM sniff_csv('my_file.csv');
返回  
Prompt = FROM read_csv('my_file.csv', auto_detect=false, delim=',', quote='"', escape='"', new_line='\n', skip=0, header=true, columns={...});

欢迎关注我的github (https://github.com/digoal/blog) , 学习数据库不迷路.  

近期正在写公开课材料, 未来将通过视频号推出, 欢迎关注视频号:

Image

文章中的参考文档请点击阅读原文获得.