Skip to content

duckDB一款神好用的資料庫

Published: at 下午05:16

duckDB 開箱即用的資料庫 也不用預先定義dll load 進去 只要會 sql 即可任意操弄

2024-12-24 目前 於 db-engines 排名為 55 距上次 2023-12 排名是91名 一年上升了36名 該是後續可期

安裝及使用

node.js 安裝

npm install duckdb

node.js 使用 假設 同一路徑下有一 json 為 all.log

const duckdb = require('duckdb');

const db = new duckdb.Database(':memory:');

const fileName = process.argv[2]

db.all(` create table tableall as select * from read_json("all.log" );`, function (err, res) {
    if (err) {
        console.warn(err);
        return;
    }
    db.all(`select  utm from  tableall group by utm`,(err,res)=>{
        if (err) {
            console.warn(err);
            return;
        }
        console.log("res: ", res)
    });



})

nodejs 略過 錯誤資料 及增加 數量 (我的電腦是 64G RM )

db.all(` create table tableall as select * from read_json("all.log",ignore_errors = true, maximum_object_size=2147483644);`, function (err, res) {

如果是用duckdb cli

使用

duckdb

如何讀取檔案 example json in windows computer

select * from read_json("C:\workspace\all.log");

做成另外一張表 讓後續可以玩耍

 create table myTable as select * from read_json("C:\workspace\all.log");

如何輸出檔案

- with json
COPY (select *  from myTable) TO "C:\workspace\output.json" WITH (FORMAT 'json');

- with csv

COPY (select *  from myTable) TO "C:\workspace\output.csv" WITH (FORMAT 'csv');

- 分隔符號
COPY (select *  from myTable) TO "C:\workspace\output.csv" WITH (FORMAT 'csv',DELIMITER '|');

如果

調整 輸出格式

.mod duckbox       <-- 此為預設

.mod box

.mod csv

.mod json

.mod table

使用紀錄

毫秒 轉 date

STRFTIME(TO_TIMESTAMP( YOUR_COL / 1000.0), '%Y-%m-%d %H:%M:%S.%f') AS formatted_ts_max,

比對大小寫

where
   REGEXP_MATCHES(YOURL_COL, '^[A-Za-z1-9]+$')

可以引入 aws 資料

INSTALL httpfs;LOAD httpfs;
INSTALL httpfs;

SET s3_region='ap-northeast-1';
SET s3_access_key_id='{{YOUR_KEY}}';
SET s3_secret_access_key='{{YOUR_ACCESS_KEY}}';

create table tmp_table as select * from read_json("s3://your_data/**/*.json.gz",union_by_name = true);

-- /**/*.json 任意路徑下的 所有.json.gz 檔案
--  union_by_name = true , 結合不同的資料結構 (如果資料結構很亂可以使用這個)

可以引入 gcs 資料

建立 key

CREATE SECRET (
    TYPE gcs,
    KEY_ID '{{YOUR_KEY_ID}}',
    SECRET '{{YOUR_SECRET}}'
);

讀取

SELECT *
FROM read_parquet('gs://gcs_bucket/file.parquet');