Debian Codegraph @

docs/source/dataframe-hive.rst

raw
1 .. _dataframe.hive:
2
3 Using Hive Partitioning with Dask
4 =================================
5
6 .. currentmodule:: dask.dataframe
7
8 It is sometimes useful to write your dataset with a hive-like directory scheme.
9 For example, if your dataframe contains ``'year'`` and ``'semester'`` columns,
10 a hive-based directory structure might look something like the following::
11
12 output-path/
13 ├── year=2022/
14 │ ├── semester=fall/
15 │ │ └── part.0.parquet
16 │ └── semester=spring/
17 │ ├── part.0.parquet
18 │ └── part.1.parquet
19 └── year=2023/
20 └── semester=fall/
21 └── part.1.parquet
22
23 The use of this self-describing structure implies that all rows within
24 the ``'output-path/year=2022/semester=fall/'`` directory will contain
25 the value ``2022`` in the ``'year'`` column and the value ``'fall'``
26 in the ``'semester'`` column.
27
28 The primary advantage of generating a hive-partitioned dataset
29 is that certain IO filters can be applied by :func:`read_parquet`
30 without the need to parse any file metadata. In other words,
31 the following command will typically be faster when the dataset
32 is already hive-partitioned on the ``'year'`` column.
33
34 .. code-block:: python
35
36 >>> dd.read_parquet("output-path", filters=[("year", ">", 2022)])
37
38 Writing Parquet Data with Hive Partitioning
39 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
40
41 Dask's :func:`to_parquet` function will produce a hive-partitioned
42 directory scheme automatically when the ``partition_on`` option is used.
43
44 .. code-block:: python
45
46 >>> df.to_parquet("output-path", partition_on=["year", "semester"])
47
48 >>> os.listdir("output-path")
49 ["year=2022", "year=2023"]
50
51 >>> os.listdir("output-path/year=2022")
52 ["semester=fall", "semester=spring"]
53
54 >>> os.listdir("output-path/year=2022/semester=spring")
55 ['part.0.parquet', 'part.1.parquet']
56
57
58 It is important to recognize that Dask will **not** aggregate the
59 data files written within each of the leaf directories. This is
60 because each of the DataFrame partitions is written independently
61 during the execution of the :func:`to_parquet` task graph. In order
62 to write out data for partition `i`, the partition-i write task will
63 perform a `groupby` operation on columns ``["year", "semester"]``,
64 and then each distinct group will be written to the corresponding
65 directory using the file name ``'part.{i}.parquet'``. Therefore, it
66 is possible for a hive-partitioned write to produce a large number
67 of files in every leaf directory (one for each DataFrame partition).
68
69 If your application requires you to produce a single parquet file
70 for each hive partition, one possible solution is to sort or shuffle
71 on the partitioning columns before calling :func:`to_parquet`.
72
73 .. code-block:: python
74
75 >>> partition_on = ["year", "semester"]
76
77 >>> df.shuffle(on=partition_on).to_parquet(partition_on=partition_on)
78
79 Using a global shuffle like this is extremely expensive, and should be
80 avoided whenever possible. However, it is also guaranteed to produce
81 the minimum number of files, which may be worth the sacrifice at times.
82
83
84 Reading Parquet Data with Hive Partitioning
85 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
86
87 In most cases, :func:`read_parquet` will process hive-partitioned
88 data automatically. By default, all hive-partitioned columns will
89 be interpreted as categorical columns.
90
91 .. code-block:: python
92
93 >>> ddf = dd.read_parquet("output-path", columns=["year", "semester"])
94
95 >>> ddf
96 Dask DataFrame Structure:
97 year semester
98 npartitions=4
99 category[known] category[known]
100 ... ...
101 ... ...
102 ... ...
103 ... ...
104 Dask Name: read-parquet, 1 graph layer
105
106 >>> ddf.compute()
107 year semester
108 0 2022 fall
109 1 2022 fall
110 2 2022 fall
111 3 2022 spring
112 4 2022 spring
113 5 2022 spring
114 6 2023 fall
115 7 2023 fall
116
117
118 Defining a Custom Partitioning Schema
119 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
120
121 It is possible to specify a custom schema for the hive-partitioned columns. The columns
122 will then be read using the specified types and not as `category`.
123
124 .. code-block:: python
125
126 >>> schema = pa.schema([("year", pa.int16()), ("semester", pa.string())])
127
128 >>> ddf2 = dd.read_parquet(
129 ... path,
130 ... columns=["year", "semester"],
131 ... dataset={"partitioning": {"flavor": "hive", "schema": schema}}
132 ... )
133 Dask DataFrame Structure:
134 year semester
135 npartitions=4
136 int16 object
137 ... ...
138 ... ...
139 ... ...
140 ... ...
141
142
143 If any of your hive-partitioned columns contain null values, you
144 **must** specify the partitioning schema in this way.
145
146 Although it is not required, we also recommend that you specify
147 the partitioning schema if you need to partition on high-cardinality
148 columns. This is because the default ``'category'`` dtype will
149 track the known categories in a way that can significantly increase
150 the overall memory footprint of your Dask collection. In fact,
151 :func:`read_parquet` already clears the "known categories" of other
152 columns for this same reason (see :doc:`dataframe-categoricals`).
153
154
155 Best Practices
156 --------------
157
158 Although hive partitioning can sometimes improve read performance
159 by simplifying filtering, it can also lead to degraded performance
160 and errors in other cases.
161
162
163 Avoid High Cardinality
164 ~~~~~~~~~~~~~~~~~~~~~~
165
166 A good rule of thumb is to avoid partitioning on `float` columns,
167 or any column containing many unique values (i.e. high cardinality).
168
169 The most common cause of poor user experience with hive partitioning
170 is high-cardinality of the partitioning column(s). For example, if
171 you try to partition on a column with millions of unique values, then
172 `:func:`to_parquet`` will need to generate millions of directories. The
173 management of these directories is likely to put strain on the file
174 system, and the need for many small files within each directory
175 is sure to compound the issue.
176
177
178 Use Simple Data Types for Partitioning
179 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
180
181 Since hive-partitioned data is "self describing," we suggest that
182 you avoid partitioning on complex data types, and opt for integer
183 or string-based data types whenever possible. If your data type
184 cannot be easily inferred from the string value used to define the
185 directory name, then the IO engine may struggle to parse the values.
186
187 For example, directly partitioning on a column with a ``datetime64``
188 dtype might produce a directory name like the following::
189
190 output-path/
191 ├── date=2022-01-01 00:00:00/
192 ├── date=2022-02-01 00:00:00/
193 ├── ...
194 └── date=2022-12-01 00:00:00/
195
196 These directory names will not be correctly interpreted as
197 ``datetime64`` values, and are even considered illegal on Windows
198 systems. For more-reliable behavior, we recommend that such a column
199 be decomposed into one or more "simple" columns. For example, one
200 could easily use ``'date'`` to construct ``'year'``, ``'month'``,
201 and ``'day'`` columns (as needed).
202
203
204 Aggregate Files at Read Time
205 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
206
207 .. warning::
208 The ``aggregate_files`` argument is currently listed as
209 experimental. However, there are currently no plans to remove
210 the argument or change it's behavior in a future release.
211
212 Since hive-partitioning will typically produce a large number of
213 small files, :func:`read_parquet` performance will usually benefit
214 from proper usage of the ``aggregate_files`` argument. Take the
215 following dataset for example::
216
217 dataset-path/
218 ├── region=1/
219 │ ├── section=a/
220 │ │ └── 01.parquet
221 │ │ └── 02.parquet
222 │ │ └── 03.parquet
223 │ ├── section=b/
224 │ └── └── 04.parquet
225 │ └── └── 05.parquet
226 └── region=2/
227 ├── section=a/
228 │ ├── 06.parquet
229 │ ├── 07.parquet
230 │ ├── 08.parquet
231
232 If we set ``aggregate_files=True`` for this case, we are telling Dask
233 that any of the parquet data files may be aggregated into the same output
234 DataFrame partition. If, instead, we specify the name of a partitioning
235 column (e.g. ``'region'`` or ``'section'``), we allow the aggregation of
236 any two files sharing a file path up to, and including, the corresponding
237 directory name. For example, if ``aggregate_files`` is set to ``'section'``,
238 ``04.parquet`` and ``05.parquet`` may be aggregated together, but
239 ``03.parquet`` and ``04.parquet`` cannot be. If, however, ``aggregate_files``
240 is set to ``'region'``, ``04.parquet`` may be aggregated with ``05.parquet``,
241 **and** ``03.parquet`` may be aggregated with ``04.parquet``.
242
243 Using ``aggregate_files`` will typically improve performance by making it
244 more likely for DataFrame partitions to approach the size specified by the
245 ``blocksize`` argument. In contrast, default behavior may produce a large
246 number of partitions that are much smaller than ``blocksize``.