Considering a DatabaseExample
included with Mathematica:
Needs["DatabaseLink`"]
conn = OpenSQLConnection["publisher"];
SQLSelect[conn, "ROYSCHED", "ShowColumnHeadings" -> True]//Short
{{TITLE_ID,LORANGE,HIRANGE,ROYALTY},{BS1011,0,5000,0.1},<<49>>,{PY2008,0,50000,0.1}}
Now with the introduction of v10 and functions such as Association
and Dataset
, we can convert this data to a Dataset
:
sqltodataset[fields_, data_] /; Equal @@ Join[{Length@fields}, Length /@ data] :=
Dataset[Association[Thread[fields -> #]] & /@ data]
data = SQLSelect[conn, "ROYSCHED", "ShowColumnHeadings" -> True];
ds = sqltodataset[First@data, Rest@data];
Querying should now be much faster:
Do[SQLSelect[conn, "ROYSCHED", {"ROYALTY"}, SQLColumn["TITLE_ID"] == "BS1001"], {100}] // Timing
Do[Normal[Select[ds, #"TITLE_ID" == "BS1001" &][[All, "ROYALTY"]]], {100}] // Timing
And it seems to be. Although not quite a fast as I expected:
{0.171601,Null}
{0.093601, Null}
But at the expense of RAM:
ByteCount[ds]
35644
Is there a real upside to converting to a Dataset
, or should I just stick to SQL to query? And is there a more direct way to convert straight to a Dataset
?
AssociationThread
in place ofAssociation[Thread[...]]
. $\endgroup$Dataset
currently is optimized to work with hierarchical data, rather than tabular. There are plans to add SQL-like backend(s) to Dataset, which will enable efficient manipulation of tabular data, but those will likely not be based on Associations in the same manner asDataset
is (namely, oneAssociation
per row in a db). $\endgroup$