| 1 |
Dask Dataframe and SQL |
| 2 |
====================== |
| 3 |
|
| 4 |
SQL is a method for executing tabular computation on database servers. |
| 5 |
Similar operations can be done on Dask Dataframes. Users commonly wish |
| 6 |
to link the two together. |
| 7 |
|
| 8 |
This document describes the connection between Dask and SQL-databases |
| 9 |
and serves to clarify several of the questions that we commonly |
| 10 |
receive from users. |
| 11 |
|
| 12 |
.. contents:: |
| 13 |
:local: |
| 14 |
:depth: 1 |
| 15 |
:backlinks: top |
| 16 |
|
| 17 |
Does Dask implement SQL? |
| 18 |
------------------------ |
| 19 |
|
| 20 |
The short answer is "no". Dask has no parser or query planner for SQL |
| 21 |
queries. However, the Pandas API, which is largely identical for |
| 22 |
Dask Dataframes, has many analogues to SQL operations. A good |
| 23 |
description for mapping SQL onto Pandas syntax can be found in the |
| 24 |
`pandas docs`_. |
| 25 |
|
| 26 |
.. _pandas docs: https://pandas.pydata.org/docs/getting_started/comparison/comparison_with_sql.html |
| 27 |
|
| 28 |
The following packages may be of interest: |
| 29 |
|
| 30 |
- `dask-sql`_ adds a SQL query engine on top of Dask. |
| 31 |
In addition to working on CPU, it offers experimental support for CUDA-enabled GPUs through RAPIDS libraries such as `cuDF`_. |
| 32 |
|
| 33 |
- `FugueSQL`_ provides a unified interface to run SQL code on a variety of different computing frameworks. |
| 34 |
Specifying ``DaskExecutionEngine`` or ``DaskSQLExecutionEngine`` as the execution engine for queries allows them to be computed using Dask or dask-sql, respectively. |
| 35 |
|
| 36 |
.. _dask-sql: https://dask-sql.readthedocs.io/en/latest/ |
| 37 |
.. _cuDF: https://docs.rapids.ai/api/cudf/stable/ |
| 38 |
.. _FugueSQL: https://fugue-tutorials.readthedocs.io/en/latest/tutorials/fugue_sql/index.html |
| 39 |
|
| 40 |
Database or Dask? |
| 41 |
----------------- |
| 42 |
|
| 43 |
A database server is able to process tabular data and produce results just like |
| 44 |
Dask Dataframe. Why would you choose to use one over the other? |
| 45 |
|
| 46 |
These days a database server can be a sharded/distributed system, capable of |
| 47 |
handling tables with millions of rows. Most database implementations are |
| 48 |
geared towards row-wise retrieval and (atomic) updates of small subset of a |
| 49 |
table. Configuring a database to be fast for a particular |
| 50 |
sort of query can be challenging, but assuming all your data is already in the |
| 51 |
database, it may well be the best solution - particularly if you understand |
| 52 |
something about SQL query plan optimisation. A SQL implementation can |
| 53 |
very efficiently analyse a query to only extract a small part of a table |
| 54 |
for consideration, when the rest is excluded by conditionals. |
| 55 |
|
| 56 |
Dask is much more flexible than a database, and designed explicitly |
| 57 |
to work with larger-than-memory datasets, in parallel, and potentially distributed |
| 58 |
across a cluster. If your workflow is not well suited to SQL, use dask. If |
| 59 |
your database server struggles with volume, dask may do better. It |
| 60 |
would be best to profile your queries |
| 61 |
(and keep in mind other users of the resources!). If you need |
| 62 |
to combine data from different sources, dask may be your best option. |
| 63 |
|
| 64 |
You may find the dask API easier to use than writing SQL (if you |
| 65 |
are already used to Pandas), and the diagnostic feedback more useful. |
| 66 |
These points can debatably be in Dask's favour. |
| 67 |
|
| 68 |
Loading from SQL with read_sql_table or read_sql_query |
| 69 |
------------------------------------------------------ |
| 70 |
|
| 71 |
Dask allows you to build dataframes from SQL tables and queries using the |
| 72 |
function :func:`dask.dataframe.read_sql_table` and :func:`dask.dataframe.read_sql_query`, |
| 73 |
based on the `Pandas version`_, sharing most arguments, and using SQLAlchemy |
| 74 |
for the actual handling of the queries. You may need to install additional |
| 75 |
driver packages for your chosen database server. |
| 76 |
|
| 77 |
.. _Pandas version: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_sql_table.html |
| 78 |
|
| 79 |
Since Dask is designed to work with larger-than-memory datasets, or be distributed |
| 80 |
on a cluster, the following are the main differences versus Pandas to watch out for |
| 81 |
|
| 82 |
- Dask does not support arbitrary text queries, only whole tables and SQLAlchemy |
| 83 |
`sql expressions`_ |
| 84 |
|
| 85 |
- the con argument must be a `URI string`_, not an SQLAlchemy engine/connection |
| 86 |
|
| 87 |
- partitioning information is *required*, which can be as simple as providing |
| 88 |
an index column argument, or can be more explicit (see below) |
| 89 |
|
| 90 |
- the chunksize argument is not used, since the partitioning must be via an |
| 91 |
index column |
| 92 |
|
| 93 |
.. _URI string: https://docs.sqlalchemy.org/en/13/core/engines.html#database-urls |
| 94 |
.. _sql expressions: https://docs.sqlalchemy.org/en/13/core/tutorial.html |
| 95 |
|
| 96 |
If you need something more flexible than this, or the |
| 97 |
method fails for you (e.g., on type inference), then skip to the next section. |
| 98 |
|
| 99 |
Why the differences |
| 100 |
^^^^^^^^^^^^^^^^^^^ |
| 101 |
|
| 102 |
Dask is intended to make processing large volumes of data possible, including |
| 103 |
potentially distributing that processing across a cluster. For the retrieval of |
| 104 |
data from SQL servers, this means that the query must be partitionable: that |
| 105 |
each partition can be fetched independently of others and not dependent on |
| 106 |
some global state, and that the definitions of the tasks must be serialisable, |
| 107 |
i.e., can be represented as a stream of bytes communicated to workers. |
| 108 |
|
| 109 |
The constraints mean that we cannot directly accept SQLAlchemy engines |
| 110 |
or connection objects, since they have internal state (buffers, etc.) |
| 111 |
that cannot be serialised. A `URI string`_ must be used, which can be |
| 112 |
recreated into a fresh engine on the workers. |
| 113 |
Similarly, we cannot accommodate chunked queries |
| 114 |
which rely on the internal state of a database cursor; nor LIMIT/OFFSET |
| 115 |
queries, which are not guaranteed to be repeatable, and involve scanning |
| 116 |
the whole query on th server (which is very inefficient). |
| 117 |
|
| 118 |
**If** your data is small enough not to require Dask's out-of-core and/or |
| 119 |
distributed capabilities, then you are probably better to use Pandas or SQLAlchemy |
| 120 |
directly. |
| 121 |
|
| 122 |
Index Column |
| 123 |
^^^^^^^^^^^^ |
| 124 |
|
| 125 |
We need a way to turn a single main query into sub-queries for each |
| 126 |
partition. For most reasonable database tables, there should be an obvious |
| 127 |
column which can be used for partitioning - it is probably numeric, |
| 128 |
and should certainly be indexed in the database. The latter condition |
| 129 |
is important, since many simultaneous queries will hit your server once |
| 130 |
Dask starts to compute. |
| 131 |
|
| 132 |
By providing just a column name for the index argument, you imply that the |
| 133 |
column is numeric, and Dask guesses a reasonable partitioning by evenly |
| 134 |
splitting the space between minimum and maximum values into ``npartitions`` |
| 135 |
intervals. You can also provide the max/min that you would like to |
| 136 |
consider so that Dask doesn't need to query for these. Alternatively, |
| 137 |
you can have Dask fetch the first few row (5 by default) and use |
| 138 |
them to guess the typical bytes/row, and base the partitioning size on |
| 139 |
this. Needless to say, the results will vary a lot for tables that are |
| 140 |
not uncommonly homogeneous. |
| 141 |
|
| 142 |
Specific partitioning |
| 143 |
^^^^^^^^^^^^^^^^^^^^^ |
| 144 |
|
| 145 |
In some cases, you may have a very good idea of how to partition the data, |
| 146 |
for example based on a column that has a finite number of unique values |
| 147 |
or categories. This enables using string columns, or anything with a |
| 148 |
natural ordering, for the index column, not only numerical types. |
| 149 |
|
| 150 |
In this case, you would provide a specific set of ``divisions``, |
| 151 |
the start/end values of the index column for each partition. For example, |
| 152 |
if a column happened to contain a random ID in hex string format, then you |
| 153 |
could specify 16 partitions with |
| 154 |
|
| 155 |
.. code-block:: python |
| 156 |
|
| 157 |
df = read_sql_table("mytable", divisions=list("0123456789abcdefh"), |
| 158 |
index_col="hexID") |
| 159 |
|
| 160 |
so the first partition would have IDs with values ``"0" <= hexID < "1"``, i.e., |
| 161 |
leading character "0". |
| 162 |
|
| 163 |
SQLAlchemy expressions |
| 164 |
^^^^^^^^^^^^^^^^^^^^^^ |
| 165 |
|
| 166 |
Since we only send the database connection URI and not the engine object, |
| 167 |
we cannot rely on SQLAlchemy's table class inference and ORM to conduct queries. However, we can |
| 168 |
use the "select" `sql expressions`_, which only get formatted into a text query at |
| 169 |
the point of execution. |
| 170 |
|
| 171 |
.. code-block:: python |
| 172 |
|
| 173 |
from sqlalchemy import sql |
| 174 |
number = sql.column("number") |
| 175 |
name = sql.column("name") |
| 176 |
s1 = sql.select([ |
| 177 |
number, name, sql.func.length(name).label("lenname") |
| 178 |
] |
| 179 |
).select_from(sql.table("test")) |
| 180 |
data = read_sql_query( |
| 181 |
s1, db, npartitions=2, index_col=number |
| 182 |
) |
| 183 |
|
| 184 |
Here we have also demonstrated the use of the function ``length`` to |
| 185 |
perform an operation server-side. Note that it is necessary to *label* such |
| 186 |
operations, but you can use them for the index column, |
| 187 |
so long as it is also |
| 188 |
in the set of selected columns. If using for the index/partitioning, the |
| 189 |
column should still be indexed in the database, for performance. |
| 190 |
One of the most important functions to consider is ``cast`` to specify the |
| 191 |
output data type or conversion in the database, if pandas is having |
| 192 |
trouble inferring the data type. |
| 193 |
|
| 194 |
You should be warned, that SQLAlchemy expressions take some time to get |
| 195 |
used to, and you can practice with Pandas first, reading only the first small |
| 196 |
chunk of a query, until things look right. You can find a more complete |
| 197 |
object-oriented example in `this gist`_ |
| 198 |
|
| 199 |
.. _this gist: https://gist.github.com/quasiben/08a7f291039db2b04c2e28e1a6c21e3b |
| 200 |
|
| 201 |
Load from SQL, manual approaches |
| 202 |
-------------------------------- |
| 203 |
|
| 204 |
If ``read_sql_table`` is not sufficient for your needs, you can try one of |
| 205 |
the following methods. |
| 206 |
|
| 207 |
From Map functions |
| 208 |
^^^^^^^^^^^^^^^^^^ |
| 209 |
|
| 210 |
Often you know more about your data and server than the generic approach above |
| 211 |
allows. Indeed, some database-like servers may simply not be supported by |
| 212 |
SQLAlchemy, or provide an alternate API which is better optimised. |
| 213 |
|
| 214 |
If you already have a way to fetch data from the database in partitions, |
| 215 |
then you can use :func:`dask.dataframe.from_map` and construct a |
| 216 |
dataframe this way. It might look something like. |
| 217 |
|
| 218 |
.. code-block:: python |
| 219 |
|
| 220 |
import dask.dataframe as dd |
| 221 |
|
| 222 |
def fetch_partition(part): |
| 223 |
conn = establish_connection() |
| 224 |
df = fetch_query(base_query.format(part)) |
| 225 |
return df.astype(known_types) |
| 226 |
|
| 227 |
ddf = dd.from_map(fetch_partition, |
| 228 |
parts, |
| 229 |
meta=known_types, |
| 230 |
divisions=div_from_parts(parts)) |
| 231 |
|
| 232 |
Where you must provide your own functions for setting up a connection to the server, |
| 233 |
your own query, and a way to format that query to be specific to each partition. |
| 234 |
For example, you might have ranges or specific unique values with a WHERE |
| 235 |
clause. The ``known_types`` here is used to transform the dataframe partition and provide |
| 236 |
a ``meta``, to help for consistency and avoid Dask having to analyse one partition |
| 237 |
up front to guess the columns/types; you may also want to explicitly set the index. |
| 238 |
|
| 239 |
Stream via client |
| 240 |
^^^^^^^^^^^^^^^^^ |
| 241 |
|
| 242 |
In some cases, the workers may not have access to data, but the client does; |
| 243 |
or the initial loading time of the data is not important, so long as the |
| 244 |
dataset is then held in cluster memory and available for dask-dataframe |
| 245 |
queries. It is possible to construct the dataframe by uploading chunks of |
| 246 |
data from the client: |
| 247 |
|
| 248 |
See a complete example of how to do this `here`_ |
| 249 |
|
| 250 |
.. _here: https://stackoverflow.com/questions/62818473/why-dasks-read-sql-table-requires-a-index-col-parameter/62821858#62821858 |
| 251 |
|
| 252 |
|
| 253 |
Access data files directly |
| 254 |
^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 255 |
|
| 256 |
Some database systems such as Apache Hive store their data in a location |
| 257 |
and format that may be directly accessible to Dask, such as parquet files |
| 258 |
on S3 or HDFS. In cases where your SQL query would read whole datasets and pass |
| 259 |
them to Dask, the streaming of data from the database is very likely the |
| 260 |
bottleneck, and it's probably faster to read the source data files directly. |
| 261 |
|
| 262 |
Query pushdown? |
| 263 |
--------------- |
| 264 |
|
| 265 |
If you define a query based on a database table, then only use some columns |
| 266 |
of the output, you may expect that Dask is able to tell the database server |
| 267 |
to only send some of the table's data. Dask is not currently able to |
| 268 |
do this "pushdown" optimisation, and you would need to change your query using |
| 269 |
the SQL expression syntax. |
| 270 |
We may be able to resolve this in the future (:issue:`6388`). |
| 271 |
|
| 272 |
If the divisions on your dataframe are well defined, then selections on the |
| 273 |
index may successfully avoid reading irrelevant partitions. |