-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo8_persist_data.py
50 lines (43 loc) · 1.3 KB
/
demo8_persist_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import duckdb
import requests
from duckdb.typing import VARCHAR
def get(url):
return requests.get(url).text
duckdb.create_function("get", get, [VARCHAR], VARCHAR)
df = duckdb.sql("""
CREATE TABLE pokemon AS
SELECT unnest(results) AS pokemon
FROM read_json_auto('https://pokeapi.co/api/v2/pokemon?limit=10');
WITH base AS (
SELECT
pokemon.name AS name,
json(get(pokemon.url)) AS details
FROM pokemon
), pokemon_details AS (
SELECT
details.id,
name,
details.abilities::STRUCT(ability STRUCT(name VARCHAR, url VARCHAR), is_hidden BOOLEAN, slot INTEGER)[] AS abilities,
details.height,
details.weight
FROM base
)
SELECT
id,
name,
[x.ability.name FOR x IN abilities] AS abilities,
height,
weight
FROM pokemon_details;
""").df()
# Continue data wrangling in Pandas
df_agg = df.explode("abilities").groupby("abilities", as_index=False).agg(count=("id", "count"))
# Persist data
with duckdb.connect(database="pokemon.db") as conn:
conn.sql("""
DROP TABLE IF EXISTS pokemon_abilities;
CREATE TABLE pokemon_abilities AS
SELECT abilities AS ability, count
FROM df_agg
ORDER BY count DESC;
""")