研究数据湖永远没有完工的一天。供应商会增加字段,成交量列因为股数溢出而改成 64 位,历史中途出现新的评级。去年写出的文件没有今天文件里的内容,但一次查询必须把它们全部读出来。Parquet 的办法是:每个文件都自带模式。
用通俗的话说这个想法
我们在哪里。 前面的主题讲的是从长得都一样的文件里少读数据。这一个讲的是长得不一样的文件:数据湖的结构会随时间变化,读取器必须协调各个版本。它使用主题 5 的分区数据湖,那里的文件夹会不断积累用不同模式写出的文件。
定义模式演进
在旧数据仍可读取的前提下,随时间修改数据集的列或类型。新增列和拓宽数值类型是安全的;重命名、删除列或改变列的含义,才是数据集出问题的地方。
新增一列,把旧文件和新文件一起读
这里旧文件有三列,新文件多了第四列 source。unified_schema 不读任何数据,只把各文件的尾部合并成一个模式。read_evolved 把这个模式交给数据集读取器,它按原样读取每个文件,并给旧行的缺失列填上空值。什么都不必重写。
# An old file (3 columns) and a newer one with a fourth column, read togetherpq.write_table(table.slice(0, 1000), "old.parquet")pq.write_table(add_column(table.slice(1000, 5), "source", "vendor-b"), "new.parquet")print(unified_schema(["old.parquet", "new.parquet"]))both = read_evolved(["old.parquet", "new.parquet"])print(both.num_rows, "rows;", both["source"].null_count, "nulls in source")print(both.slice(998, 4).to_pylist()[1:3])
[('symbol', 'string'), ('date', 'date32[day]'), ('close', 'double'), ('source', 'string')]
1005 rows; 1000 nulls in source
[{'symbol': 'AAPL', 'date': datetime.date(2003, 12, 24), 'close': 0.305937, 'source': None}, {'symbol': 'AAPL', 'date': datetime.date(2003, 12, 26), 'close': 0.311343, 'source': 'vendor-b'}]拓宽类型
32 位的成交量在够用时没有问题,直到某天不够用。转成 64 位会保留所有值,是安全的改动,但已写出的文件仍然写着 int32,读取器不会去猜。widen 用转换后的列重写一个文件并保持原文件不动,因此你可以先验证新文件再替换。反方向的缩窄则可能悄悄丢失数值。
# A file with float32 closes, rewritten with float64 closes; the original stays as it wassmall = table.slice(0, 1000)small = small.set_column(2, "close", small["close"].cast("float32"))pq.write_table(small, "small.parquet")print("before:", pq.read_schema("small.parquet").field("close").type)print("after :", widen("small.parquet", "big.parquet", "close", "float64"))print("original still:", pq.read_schema("small.parquet").field("close").type)
before: float after : double original still: float
# The danger: two files that disagree on a type cannot be mergedtry: unified_schema(["old.parquet", "small.parquet"]) print("merged: a float32 and a float64 column do not agree, so this line should not print")except Exception as error: print(type(error).__name__ + ":", str(error)[:70])
ArrowTypeError: Unable to merge: Field close has incompatible types: double vs float
重命名看起来像删除加新增
Parquet 按名称匹配列,所以在新文件中把 px 改名为 close,会让旧文件看起来没有 close,新文件看起来没有 px。更好的做法是新增新名称,一段时间内两者都填,等所有读取方迁移完再删除旧列。含义的变化(复权价还是原始价)要当作新列,绝不要悄悄改动。
任务要求
- 1`add_column`
table.append_column(name, pa.array([value] * table.num_rows))。 - 2`unified_schema` 与 `read_evolved`
pa.unify_schemas([pq.read_schema(p) ...])得到合并后的模式;把它作为schema=传给ds.dataset(paths, format="parquet"),再调用.to_table()。 - 3`widen`读取表,用转换为
pa.type_for_alias(new_type)的列做set_column,写出path_out,并返回从中读回的str(type)。
快速检查
供应商在 2024 年起写出的文件中把
px 改名为 close。按名称合并所有文件的读取器会看到什么?请选择一个答案。
实验:评分内容
4 个任务 · 100 分- 添加一列:
add_column25 分 - 合并模式:
unified_schema25 分 - 读取形状不同的文件:
read_evolved25 分 - 安全地拓宽类型:
widen25 分