SKILL.md.backup 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. # Cloudflare R2 SQL Skill
  2. Guide for using Cloudflare R2 SQL - serverless distributed query engine for Apache Iceberg tables in R2 Data Catalog.
  3. ## Overview
  4. R2 SQL is Cloudflare's serverless distributed analytics query engine for querying Apache Iceberg tables in R2 Data Catalog. Features:
  5. - Serverless - no clusters to manage
  6. - Distributed - leverages Cloudflare's global network
  7. - Zero egress fees - query from any cloud/region
  8. - Open beta - free during beta (standard R2 storage costs apply)
  9. ## Core Concepts
  10. ### Apache Iceberg Table Format
  11. - Open table format for large-scale analytics datasets
  12. - ACID transactions for reliable concurrent reads/writes
  13. - Schema evolution - add/rename/drop columns without rewriting data
  14. - Optimized metadata - avoids full table scans via indexed metadata
  15. - Supported by Spark, Trino, Snowflake, DuckDB, ClickHouse, PyIceberg
  16. ### R2 Data Catalog
  17. - Managed Apache Iceberg catalog built into R2 bucket
  18. - Exposes standard Iceberg REST catalog interface
  19. - Single source of truth for table metadata
  20. - Tracks table state via immutable snapshots
  21. - Supports multiple query engines safely accessing same tables
  22. ### Architecture
  23. **Query Planner**:
  24. - Top-down metadata investigation
  25. - Multi-layer pruning (partition-level, column-level, row-group level)
  26. - Streaming pipeline - execution starts before planning completes
  27. - Early termination - stops when result complete without full scan
  28. - Uses partition stats and column stats (min/max, null counts)
  29. **Query Execution**:
  30. - Coordinator distributes work to workers across Cloudflare network
  31. - Workers run Apache DataFusion for parallel query execution
  32. - Arrow IPC format for inter-process communication
  33. - Parquet column pruning - reads only required columns
  34. - Ranged reads from R2 for efficiency
  35. **Aggregation Strategies**:
  36. - Scatter-gather - for simple aggregations (sum, count, avg)
  37. - Shuffling - for ORDER BY/HAVING on aggregates via hash partitioning
  38. ## Setup & Configuration
  39. ### 1. Enable R2 Data Catalog
  40. CLI:
  41. ```bash
  42. npx wrangler r2 bucket catalog enable <bucket-name>
  43. ```
  44. Note the Warehouse name and Catalog URI from output.
  45. Dashboard:
  46. 1. R2 Object Storage → Select bucket
  47. 2. Settings tab → R2 Data Catalog → Enable
  48. 3. Note Catalog URI and Warehouse name
  49. ### 2. Create API Token
  50. Required permissions: R2 Admin Read & Write (includes R2 SQL Read)
  51. Dashboard:
  52. 1. R2 Object Storage → Manage API tokens
  53. 2. Create API token → Admin Read & Write
  54. 3. Save token value
  55. ### 3. Configure Environment
  56. ```bash
  57. export WRANGLER_R2_SQL_AUTH_TOKEN=<your-token>
  58. ```
  59. Or `.env` file:
  60. ```
  61. WRANGLER_R2_SQL_AUTH_TOKEN=<your-token>
  62. ```
  63. ## Common Code Patterns
  64. ### Wrangler CLI Query
  65. ```bash
  66. npx wrangler r2 sql query "<warehouse-name>" "
  67. SELECT *
  68. FROM namespace.table_name
  69. WHERE condition
  70. LIMIT 10"
  71. ```
  72. ### PyIceberg Setup
  73. ```python
  74. from pyiceberg.catalog.rest import RestCatalog
  75. catalog = RestCatalog(
  76. name="my_catalog",
  77. warehouse="<WAREHOUSE>",
  78. uri="<CATALOG_URI>",
  79. token="<TOKEN>",
  80. )
  81. # Create namespace
  82. catalog.create_namespace_if_not_exists("default")
  83. ```
  84. ### Create Table
  85. ```python
  86. import pyarrow as pa
  87. # Define schema
  88. df = pa.table({
  89. "id": [1, 2, 3],
  90. "name": ["Alice", "Bob", "Charlie"],
  91. "score": [80.0, 92.5, 88.0],
  92. })
  93. # Create table
  94. table = catalog.create_table(
  95. ("default", "people"),
  96. schema=df.schema,
  97. )
  98. ```
  99. ### Append Data
  100. ```python
  101. table.append(df)
  102. ```
  103. ### Query Table
  104. ```python
  105. # Scan and convert to Pandas
  106. scanned = table.scan().to_arrow()
  107. print(scanned.to_pandas())
  108. ```
  109. ## SQL Reference
  110. ### Query Structure
  111. ```sql
  112. SELECT column_list | aggregation_function
  113. FROM table_name
  114. WHERE conditions
  115. [GROUP BY column_list]
  116. [HAVING conditions]
  117. [ORDER BY partition_key [DESC | ASC]]
  118. [LIMIT number]
  119. ```
  120. ### Schema Discovery
  121. ```sql
  122. -- List namespaces
  123. SHOW DATABASES;
  124. SHOW NAMESPACES;
  125. -- List tables
  126. SHOW TABLES IN namespace_name;
  127. -- Describe table
  128. DESCRIBE namespace_name.table_name;
  129. ```
  130. ### SELECT Patterns
  131. ```sql
  132. -- All columns
  133. SELECT * FROM ns.table;
  134. -- Specific columns
  135. SELECT user_id, timestamp, status FROM ns.table;
  136. -- With conditions
  137. SELECT * FROM ns.table
  138. WHERE timestamp BETWEEN '2025-01-01T00:00:00Z' AND '2025-01-31T23:59:59Z'
  139. AND status = 200
  140. LIMIT 100;
  141. -- Complex conditions
  142. SELECT * FROM ns.table
  143. WHERE (status = 404 OR status = 500)
  144. AND method = 'POST'
  145. AND user_agent IS NOT NULL
  146. ORDER BY timestamp DESC;
  147. ```
  148. ### Aggregations
  149. Supported functions: COUNT(*), SUM(col), AVG(col), MIN(col), MAX(col)
  150. ```sql
  151. -- Count by group
  152. SELECT department, COUNT(*)
  153. FROM ns.sales_data
  154. GROUP BY department;
  155. -- Multiple aggregates
  156. SELECT region, MIN(price), MAX(price), AVG(price)
  157. FROM ns.products
  158. GROUP BY region
  159. ORDER BY AVG(price) DESC;
  160. -- With HAVING filter
  161. SELECT category, SUM(amount)
  162. FROM ns.sales
  163. WHERE sale_date >= '2024-01-01'
  164. GROUP BY category
  165. HAVING SUM(amount) > 10000
  166. LIMIT 10;
  167. ```
  168. ### Data Types
  169. | Type | Description | Example |
  170. |------|-------------|---------|
  171. | integer | Whole numbers | 1, 42, -10 |
  172. | float | Decimals | 1.5, 3.14 |
  173. | string | Text (quoted) | 'hello', 'GET' |
  174. | boolean | true/false | true, false |
  175. | timestamp | RFC3339 | '2025-01-01T00:00:00Z' |
  176. | date | YYYY-MM-DD | '2025-01-01' |
  177. ### Operators
  178. Comparison: =, !=, <, <=, >, >=, LIKE, BETWEEN, IS NULL, IS NOT NULL
  179. Logical: AND (higher precedence), OR (lower precedence)
  180. ### ORDER BY Limitations
  181. **CRITICAL**: ORDER BY only supports partition key columns
  182. ```sql
  183. -- Valid if timestamp is partition key
  184. SELECT * FROM ns.logs ORDER BY timestamp DESC LIMIT 100;
  185. -- Invalid if column not in partition key
  186. SELECT * FROM ns.logs ORDER BY user_id; -- ERROR
  187. ```
  188. ### LIMIT Defaults
  189. - Range: 1 to 10,000
  190. - Default: 500 if not specified
  191. ## Pipelines Integration
  192. ### Create Pipeline with Data Catalog Sink
  193. Schema file (`schema.json`):
  194. ```json
  195. {
  196. "fields": [
  197. {"name": "user_id", "type": "string", "required": true},
  198. {"name": "event_type", "type": "string", "required": true},
  199. {"name": "amount", "type": "float64", "required": false}
  200. ]
  201. }
  202. ```
  203. Setup:
  204. ```bash
  205. npx wrangler pipelines setup
  206. ```
  207. Configuration:
  208. - Pipeline name: ecommerce
  209. - Enable HTTP endpoint: yes
  210. - Schema: Load from file → schema.json
  211. - Destination: Data Catalog Table
  212. - R2 bucket: your-bucket
  213. - Namespace: default
  214. - Table name: events
  215. - Catalog token: <your-token>
  216. - Compression: zstd
  217. - Roll file time: 10 seconds (dev), 300+ (prod)
  218. ### Send Data to Pipeline
  219. ```bash
  220. curl -X POST https://{stream-id}.ingest.cloudflare.com \
  221. -H "Content-Type: application/json" \
  222. -d '[
  223. {
  224. "user_id": "user_123",
  225. "event_type": "purchase",
  226. "amount": 29.99
  227. }
  228. ]'
  229. ```
  230. ## Common Use Cases
  231. ### Log Analytics
  232. - Ingest logs via Pipelines to Iceberg table
  233. - Partition by day(timestamp) for efficient queries
  234. - Query specific time ranges with automatic pruning
  235. - Aggregate by status codes, endpoints, user agents
  236. ```sql
  237. SELECT status, COUNT(*)
  238. FROM logs.http_requests
  239. WHERE timestamp BETWEEN '2025-01-01T00:00:00Z' AND '2025-01-31T23:59:59Z'
  240. AND method = 'GET'
  241. GROUP BY status
  242. ORDER BY COUNT(*) DESC;
  243. ```
  244. ### Fraud Detection
  245. - Stream transaction events to catalog
  246. - Query suspicious patterns with WHERE filters
  247. - Aggregate by location, merchant, time windows
  248. ```sql
  249. SELECT location, COUNT(*), AVG(amount)
  250. FROM fraud.transactions
  251. WHERE is_fraud = true
  252. AND transaction_timestamp >= '2025-01-01'
  253. GROUP BY location
  254. HAVING COUNT(*) > 10;
  255. ```
  256. ### Business Intelligence
  257. - ETL data into partitioned Iceberg tables
  258. - Run analytical queries across large datasets
  259. - Generate reports with GROUP BY aggregations
  260. - No egress fees when querying from BI tools
  261. ```sql
  262. SELECT
  263. department,
  264. SUM(revenue) as total_revenue,
  265. AVG(revenue) as avg_revenue
  266. FROM sales.transactions
  267. WHERE sale_date >= '2024-01-01'
  268. GROUP BY department
  269. ORDER BY SUM(revenue) DESC
  270. LIMIT 10;
  271. ```
  272. ## Performance Optimization
  273. ### Partitioning Strategy
  274. - Choose partition key based on common query patterns
  275. - Typical: day(timestamp), hour(timestamp), region, category
  276. - Enables metadata pruning to skip entire partitions
  277. - Required for ORDER BY optimization
  278. ### Query Optimization
  279. - Use WHERE filters to leverage partition/column stats
  280. - Specify LIMIT to enable early termination
  281. - ORDER BY partition key columns only
  282. - Filter on high-selectivity columns first
  283. ### Data Organization
  284. - Smaller files → slower queries (overhead)
  285. - Larger files → better compression, fewer metadata ops
  286. - Recommended: 100-500MB Parquet files after compression
  287. - Use appropriate roll intervals in Pipelines (300+ seconds for prod)
  288. ### File Pruning
  289. Automatic at three levels:
  290. 1. Partition-level: Skip manifests not matching query
  291. 2. File-level: Skip Parquet files via column stats
  292. 3. Row-group level: Skip row groups within files
  293. ## Iceberg Metadata Structure
  294. ```
  295. bucket/
  296. metadata/
  297. snap-{id}.avro # Snapshot (points to manifest list)
  298. {uuid}-m0.avro # Manifest file (lists data files + stats)
  299. version-hint.text # Current metadata version
  300. v{n}.metadata.json # Table metadata (schema, snapshots)
  301. data/
  302. 00000-0-{uuid}.parquet # Data files
  303. ```
  304. **Metadata hierarchy**:
  305. 1. Table metadata JSON - schema, partition spec, snapshot log
  306. 2. Snapshot - points to manifest list
  307. 3. Manifest list - partition stats for each manifest
  308. 4. Manifest files - column stats for each data file
  309. 5. Parquet files - row group stats in footer
  310. ## Limitations & Best Practices
  311. ### Current Limitations (Open Beta)
  312. - ORDER BY only on partition key columns
  313. - COUNT(*) only - COUNT(column) not supported
  314. - No aliases in SELECT
  315. - No subqueries, joins, or CTEs
  316. - No nested column access
  317. - LIMIT max 10,000
  318. ### Best Practices
  319. - Partition by time dimension for time-series data
  320. - Use BETWEEN for time ranges (leverages partition pruning)
  321. - Combine filters with AND for better pruning
  322. - Set appropriate LIMIT based on use case
  323. - Use compression (zstd recommended)
  324. - Monitor query performance and adjust partitioning
  325. ### Type Safety
  326. - Quote string values: 'value'
  327. - Use RFC3339 for timestamps: '2025-01-01T00:00:00Z'
  328. - Use YYYY-MM-DD for dates: '2025-01-01'
  329. - No implicit type conversions
  330. ## Connecting Other Engines
  331. R2 Data Catalog supports standard Iceberg REST catalog API.
  332. ### Spark (Scala)
  333. ```scala
  334. val spark = SparkSession.builder()
  335. .config("spark.sql.catalog.my_catalog", "org.apache.iceberg.spark.SparkCatalog")
  336. .config("spark.sql.catalog.my_catalog.catalog-impl", "org.apache.iceberg.rest.RESTCatalog")
  337. .config("spark.sql.catalog.my_catalog.uri", catalogUri)
  338. .config("spark.sql.catalog.my_catalog.token", token)
  339. .config("spark.sql.catalog.my_catalog.warehouse", warehouse)
  340. .getOrCreate()
  341. ```
  342. ### Snowflake
  343. - Create external Iceberg catalog connection
  344. - Configure with Catalog URI and R2 credentials
  345. - Query tables via SQL interface
  346. ### DuckDB, Trino, ClickHouse
  347. - Supported via Iceberg REST catalog protocol
  348. - Refer to engine-specific documentation for configuration
  349. ## Pricing (Future)
  350. Currently in open beta - no charges beyond standard R2 costs.
  351. Planned future pricing:
  352. - R2 storage: $0.015/GB-month
  353. - Class A operations: $4.50/million
  354. - Class B operations: $0.36/million
  355. - Catalog operations: $9.00/million (create table, get metadata, etc)
  356. - Compaction: $0.05/GB + $4.00/million objects processed
  357. - Egress: $0 (always free)
  358. 30+ days notice before billing begins.
  359. ## Troubleshooting
  360. ### Common Errors
  361. **"ORDER BY column not in partition key"**
  362. - Only partition key columns can be used in ORDER BY
  363. - Check table partition spec with DESCRIBE
  364. - Remove ORDER BY or adjust table partitioning
  365. **"Token authentication failed"**
  366. - Verify WRANGLER_R2_SQL_AUTH_TOKEN is set
  367. - Ensure token has R2 Admin Read & Write + SQL Read permissions
  368. - Token may be expired - create new one
  369. **"Table not found"**
  370. - Verify namespace exists: SHOW DATABASES
  371. - Check table name: SHOW TABLES IN namespace
  372. - Ensure catalog enabled on bucket
  373. **"No data returned"**
  374. - Check WHERE conditions match data
  375. - Verify time range in BETWEEN clause
  376. - Try removing filters to confirm data exists
  377. ### Performance Issues
  378. **Slow queries**:
  379. - Check partition pruning effectiveness
  380. - Reduce LIMIT if scanning too much data
  381. - Ensure filters on partition key columns
  382. - Review Parquet file sizes (aim for 100-500MB)
  383. **Query timeout**:
  384. - Add more restrictive WHERE filters
  385. - Reduce LIMIT
  386. - Consider better partitioning strategy
  387. ## Resources
  388. - Docs: https://developers.cloudflare.com/r2-sql/
  389. - Data Catalog: https://developers.cloudflare.com/r2/data-catalog/
  390. - Blog: https://blog.cloudflare.com/r2-sql-deep-dive/
  391. - Discord: https://discord.cloudflare.com/
  392. ## Key Reminders
  393. 1. R2 SQL queries ONLY Apache Iceberg tables in R2 Data Catalog
  394. 2. Enable catalog on bucket before use
  395. 3. Create API token with R2 + catalog permissions
  396. 4. Partition by time for time-series data
  397. 5. ORDER BY limited to partition key columns
  398. 6. Use LIMIT and WHERE for optimal performance
  399. 7. Zero egress fees - query from anywhere
  400. 8. Open beta - free during testing phase
  401. 9. Serverless - no infrastructure management
  402. 10. Leverage Cloudflare's global network for distributed execution