本文通過一個完整的樣本,協助您快速瞭解如何在EMR Serverless Spark中使用DuckDB SQL進行資料分析。樣本將示範如何建立DuckDB會話、讀取OSS上的CSV資料檔案、執行查詢分析。
情境說明
假設您是一名資料分析師,需要分析儲存在OSS上的電商訂單資料。訂單資料以CSV格式儲存,包含訂單ID、客戶名稱、商品名稱、數量、單價和訂單日期。您需要完成以下分析任務:
-
查看訂單資料的整體情況。
-
統計各商品的銷售總額。
樣本訂單資料(demo.csv)內容如下:
order_id,customer,product,quantity,price,order_date
1001,Alice,Laptop,1,6999.00,2024-01-15
1002,Bob,Wireless Mouse,2,129.00,2024-01-15
1003,Charlie,Mechanical Keyboard,1,459.00,2024-01-16
1004,Alice,Monitor,1,2499.00,2024-01-16
1005,David,Wireless Mouse,3,129.00,2024-01-17
1006,Bob,Laptop,1,6999.00,2024-01-17
1007,Charlie,USB Hub,2,89.00,2024-01-18
1008,Alice,Mechanical Keyboard,1,459.00,2024-01-18
請將樣本資料上傳至您的OSS儲存空間。後續樣本中的OSS路徑oss://your-bucket/demo/orders.csv請替換為實際路徑。
前提條件
-
已建立Serverless Spark工作空間。具體操作,請參見建立工作空間。
-
已開通OSS服務並建立儲存空間,且Serverless Spark工作空間的執行角色具備對該儲存空間的存取權限。
步驟一:建立DuckDB會話
-
在左側導覽列,選擇。
-
在Spark頁面,單擊目標工作空間名稱。
-
在左側導覽列,單擊会话管理。
-
在会话管理頁面,單擊DuckDB會話頁簽。
-
單擊建立DuckDB會話,填寫會話名稱(例如
duckdb-demo),選擇部署隊列和引擎版本,填寫需要的資源配置,單擊创建。 -
等待工作階段狀態變為运行中。
更多會話配置說明,請參見DuckDB會話。
步驟二:建立DuckDB SQL任務
-
在左側導覽列,單擊数据开发。
-
單擊新建任务,在對話方塊中選擇,輸入任務名稱(例如
orders-analysis),單擊确定。 -
在右上方選擇已建立的DuckDB會話
duckdb-demo。
步驟三:查看訂單資料
在任務編輯器中輸入以下SQL語句,讀取OSS上的CSV檔案並查看資料。請將樣本中的OSS路徑替換為您的實際路徑。
-
查看訂單資料全部內容。
SELECT * FROM 'oss://your-bucket/demo/orders.csv';返回結果如下:
order_id
customer
product
quantity
price
order_date
1001
Alice
Laptop
1
6999.00
2024-01-15
1002
Bob
Wireless Mouse
2
129.00
2024-01-15
1003
Charlie
Mechanical Keyboard
1
459.00
2024-01-16
1004
Alice
Monitor
1
2499.00
2024-01-16
1005
David
Wireless Mouse
3
129.00
2024-01-17
1006
Bob
Laptop
1
6999.00
2024-01-17
1007
Charlie
USB Hub
2
89.00
2024-01-18
1008
Alice
Mechanical Keyboard
1
459.00
2024-01-18
-
查看資料總量和日期範圍。
SELECT count(*) AS total_orders, count(DISTINCT customer) AS total_customers, count(DISTINCT product) AS total_products, min(order_date) AS first_date, max(order_date) AS last_date FROM 'oss://your-bucket/demo/orders.csv';預期返回結果如下:
total_orders
total_customers
total_products
first_date
last_date
8
4
5
2024-01-15
2024-01-18
步驟四:分析訂單資料
-
統計各商品的銷售總額,並按銷售額降序排列。
SELECT product AS product_name, sum(quantity) AS total_qty, sum(quantity * price) AS total_amount FROM 'oss://your-bucket/demo/orders.csv' GROUP BY product ORDER BY total_amount DESC;預期返回結果如下:
product_name
total_qty
total_amount
Laptop
2
13998.00
Monitor
1
2499.00
Mechanical Keyboard
2
918.00
Wireless Mouse
5
645.00
USB Hub
2
178.00
-
統計各客戶的消費情況。
SELECT customer AS customer_name, count(*) AS order_count, sum(quantity * price) AS total_spent FROM 'oss://your-bucket/demo/orders.csv' GROUP BY customer ORDER BY total_spent DESC;預期返回結果如下:
customer_name
order_count
total_spent
Alice
3
9957.00
Bob
2
7257.00
Charlie
2
637.00
David
1
387.00
後續步驟
-
瞭解DuckDB SQL開發的完整功能,請參見DuckDBSQL開發。
-
瞭解DuckDB會話的詳細配置和管理,請參見DuckDB會話。
-
瞭解資料目錄的管理和使用,請參見管理資料目錄。
-
DuckDB更多功能使用,請參考DuckDB的官方文檔。