-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathrecipe.py
More file actions
1527 lines (1234 loc) · 56.3 KB
/
recipe.py
File metadata and controls
1527 lines (1234 loc) · 56.3 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from ..utils import DataikuException
from .utils import DSSTaggableObjectSettings
from .discussion import DSSObjectDiscussions
import json, logging, warnings
from .utils import DSSTaggableObjectListItem, DSSTaggableObjectSettings
try:
basestring
except NameError:
basestring = str
class DSSRecipeListItem(DSSTaggableObjectListItem):
"""An item in a list of recipes. Do not instantiate this class, use :meth:`dataikuapi.dss.project.DSSProject.list_recipes`"""
def __init__(self, client, data):
super(DSSRecipeListItem, self).__init__(data)
self.client = client
def to_recipe(self):
"""Gets the :class:`DSSRecipe` corresponding to this dataset"""
return DSSRecipe(self.client, self._data["projectKey"], self._data["name"])
@property
def name(self):
return self._data["name"]
@property
def id(self):
return self._data["name"]
@property
def type(self):
return self._data["type"]
class DSSRecipe(object):
"""
A handle to an existing recipe on the DSS instance.
Do not create this directly, use :meth:`dataikuapi.dss.project.DSSProject.get_recipe`
"""
def __init__(self, client, project_key, recipe_name):
self.client = client
self.project_key = project_key
self.recipe_name = recipe_name
@property
def id(self):
"""The id of the recipe"""
return self.recipe_name
@property
def name(self):
"""The name of the recipe"""
return self.recipe_name
def compute_schema_updates(self):
"""
Computes which updates are required to the outputs of this recipe.
The required updates are returned as a :class:`RequiredSchemaUpdates` object, which then
allows you to :meth:`~RequiredSchemaUpdates.apply` the changes.
Usage example:
.. code-block:: python
required_updates = recipe.compute_schema_updates()
if required_updates.any_action_required():
print("Some schemas will be updated")
# Note that you can call apply even if no changes are required. This will be noop
required_updates.apply()
"""
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s/schema-update" % (self.project_key, self.recipe_name))
return RequiredSchemaUpdates(self, data)
def run(self, job_type="NON_RECURSIVE_FORCED_BUILD", partitions=None, wait=True, no_fail=False):
"""
Starts a new job to run this recipe and wait for it to complete.
Raises if the job failed.
.. code-block:: python
job = recipe.run()
print("Job %s done" % job.id)
:param job_type: The job type. One of RECURSIVE_BUILD, NON_RECURSIVE_FORCED_BUILD or RECURSIVE_FORCED_BUILD
:param partitions: If the outputs are partitioned, a list of partition ids to build
:param no_fail: if True, does not raise if the job failed.
:return: the :class:`dataikuapi.dss.job.DSSJob` job handle corresponding to the built job
:rtype: :class:`dataikuapi.dss.job.DSSJob`
"""
project = self.client.get_project(self.project_key)
outputs = project.get_flow().get_graph().get_successor_computables(self)
if len(outputs) == 0:
raise Exception("recipe has no outputs, can't run it")
first_output = outputs[0]
object_type_map = {
"COMPUTABLE_DATASET": "DATASET",
"COMPUTABLE_FOLDER": "MANAGED_FOLDER",
"COMPUTABLE_SAVED_MODEL": "SAVED_MODEL",
"COMPUTABLE_STREAMING_ENDPOINT": "STREAMING_ENDPOINT",
"COMPUTABLE_MODEL_EVALUATION_STORE": "MODEL_EVALUATION_STORE"
}
if first_output["type"] in object_type_map:
jd = project.new_job(job_type)
jd.with_output(first_output["ref"], object_type=object_type_map[first_output["type"]], partition=partitions)
else:
raise Exception("Recipe has unsupported output type {}, can't run it".format(first_output["type"]))
if wait:
return jd.start_and_wait(no_fail)
else:
return jd.start()
def delete(self):
"""
Delete the recipe
"""
return self.client._perform_empty(
"DELETE", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name))
def get_settings(self):
"""
Gets the settings of the recipe, as a :class:`DSSRecipeSettings` or one of its subclasses.
Some recipes have a dedicated class for the settings, with additional helpers to read and modify the settings
Once you are done modifying the returned settings object, you can call :meth:`~DSSRecipeSettings.save` on it
in order to save the modifications to the DSS recipe
"""
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name))
type = data["recipe"]["type"]
if type == "grouping":
return GroupingRecipeSettings(self, data)
elif type == "window":
return WindowRecipeSettings(self, data)
elif type == "sync":
return SyncRecipeSettings(self, data)
elif type == "sort":
return SortRecipeSettings(self, data)
elif type == "topn":
return TopNRecipeSettings(self, data)
elif type == "distinct":
return DistinctRecipeSettings(self, data)
elif type == "join":
return JoinRecipeSettings(self, data)
elif type == "vstack":
return StackRecipeSettings(self, data)
elif type == "sampling":
return SamplingRecipeSettings(self, data)
elif type == "split":
return SplitRecipeSettings(self, data)
elif type == "prepare" or type == "shaker":
return PrepareRecipeSettings(self, data)
#elif type == "prediction_scoring":
#elif type == "clustering_scoring":
elif type == "download":
return DownloadRecipeSettings(self, data)
#elif type == "sql_query":
# return WindowRecipeSettings(self, data)
elif type in ["python", "r", "sql_script", "pyspark", "sparkr", "spark_scala", "shell"]:
return CodeRecipeSettings(self, data)
else:
return DSSRecipeSettings(self, data)
def get_definition_and_payload(self):
"""
Deprecated. Use :meth:`get_settings`
"""
warnings.warn("Recipe.get_definition_and_payload is deprecated, please use get_settings", DeprecationWarning)
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name))
return DSSRecipeDefinitionAndPayload(self, data)
def set_definition_and_payload(self, definition):
"""
Deprecated. Use :meth:`get_settings` and :meth:`DSSRecipeSettings.save`
"""
warnings.warn("Recipe.set_definition_and_payload is deprecated, please use get_settings", DeprecationWarning)
definition._payload_to_str()
return self.client._perform_json(
"PUT", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name),
body=definition.data)
def get_status(self):
"""
Gets the status of this recipe (status messages, engines status, ...)
:return: a :class:`dataikuapi.dss.recipe.DSSRecipeStatus` object to interact with the status
:rtype: :class:`dataikuapi.dss.recipe.DSSRecipeStatus`
"""
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s/status" % (self.project_key, self.recipe_name))
return DSSRecipeStatus(self.client, data)
def get_metadata(self):
"""
Get the metadata attached to this recipe. The metadata contains label, description
checklists, tags and custom metadata of the recipe
:returns: a dict. For more information on available metadata, please see
https://doc.dataiku.com/dss/api/8.0/rest/
:rtype dict
"""
return self.client._perform_json(
"GET", "/projects/%s/recipes/%s/metadata" % (self.project_key, self.recipe_name))
def set_metadata(self, metadata):
"""
Set the metadata on this recipe.
:params dict metadata: the new state of the metadata for the recipe. You should only set a metadata object
that has been retrieved using the get_metadata call.
"""
return self.client._perform_json(
"PUT", "/projects/%s/recipes/%s/metadata" % (self.project_key, self.recipe_name),
body=metadata)
def get_object_discussions(self):
"""
Get a handle to manage discussions on the recipe
:returns: the handle to manage discussions
:rtype: :class:`dataikuapi.discussion.DSSObjectDiscussions`
"""
return DSSObjectDiscussions(self.client, self.project_key, "RECIPE", self.recipe_name)
def get_continuous_activity(self):
"""
Return a handle on the associated recipe
"""
from .continuousactivity import DSSContinuousActivity
return DSSContinuousActivity(self.client, self.project_key, self.recipe_name)
def move_to_zone(self, zone):
"""
Moves this object to a flow zone
:param object zone: a :class:`dataikuapi.dss.flow.DSSFlowZone` where to move the object
"""
if isinstance(zone, basestring):
zone = self.client.get_project(self.project_key).get_flow().get_zone(zone)
zone.add_item(self)
class DSSRecipeStatus(object):
"""Status of a recipce.
Do not create that directly, use :meth:`DSSRecipe.get_status`"""
def __init__(self, client, data):
"""Do not call that directly, use :meth:`dataikuapi.dss.recipe.DSSRecipe.get_status`"""
self.client = client
self.data = data
def get_selected_engine_details(self):
"""
Gets the selected engine for this recipe (for recipes that support engines)
:returns: a dict of the details of the selected recipe. The dict will contain at least fields 'type' indicating
which engine it is, "statusWarnLevel" which indicates whether the engine is OK / WARN / ERROR
:rtype: dict
"""
if not "selectedEngine" in self.data:
raise ValueError("This recipe doesn't have a selected engine")
return self.data["selectedEngine"]
def get_engines_details(self):
"""
Gets details about all possible engines for this recipe (for recipes that support engines)
:returns: a list of dict of the details of each possible engine. The dict for each engine
will contain at least fields 'type' indicating
which engine it is, "statusWarnLevel" which indicates whether the engine is OK / WARN / ERROR
:rtype: list
"""
if not "engines" in self.data:
raise ValueError("This recipe doesn't have engines")
return self.data["engines"]
def get_status_severity(self):
"""Returns whether the recipe is in SUCCESS, WARNING or ERROR status
:rtype: string
"""
return self.data["allMessagesForFrontend"]["maxSeverity"]
def get_status_messages(self):
"""
Returns status messages for this recipe.
:returns: a list of dict, for each status message. Each dict represents a single message,
and contains at least a "severity" field (SUCCESS, WARNING or ERROR)
and a "message" field
:rtype: list
"""
return self.data["allMessagesForFrontend"]["messages"]
class DSSRecipeSettings(DSSTaggableObjectSettings):
"""
Settings of a recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
def __init__(self, recipe, data):
super(DSSRecipeSettings, self).__init__(data["recipe"])
self.recipe = recipe
self.data = data
self.recipe_settings = self.data["recipe"]
self._str_payload = self.data.get("payload", None)
self._obj_payload = None
def save(self):
"""
Saves back the recipe in DSS.
"""
self._payload_to_str()
return self.recipe.client._perform_json(
"PUT", "/projects/%s/recipes/%s" % (self.recipe.project_key, self.recipe.recipe_name),
body=self.data)
@property
def type(self):
return self.recipe_settings["type"]
@property
def str_payload(self):
"""The raw "payload" of the recipe, as a string"""
self._payload_to_str()
return self._str_payload
@str_payload.setter
def str_payload(self, payload):
self._str_payload = payload
self._obj_payload = None
@property
def obj_payload(self):
"""The raw "payload" of the recipe, as a dict"""
self._payload_to_obj()
return self._obj_payload
@property
def raw_params(self):
"""The raw 'params' field of the recipe settings, as a dict"""
return self.recipe_settings["params"]
def _payload_to_str(self):
if self._obj_payload is not None:
self._str_payload = json.dumps(self._obj_payload)
self._obj_payload = None
if self._str_payload is not None:
self.data["payload"] = self._str_payload
def _payload_to_obj(self):
if self._str_payload is not None:
self._obj_payload = json.loads(self._str_payload)
self._str_payload = None
def get_recipe_raw_definition(self):
"""
Get the recipe definition as a raw dict
:rtype dict
"""
return self.recipe_settings
def get_recipe_inputs(self):
"""
Get a structured dict of inputs to this recipe
:rtype dict
"""
return self.recipe_settings.get('inputs')
def get_recipe_outputs(self):
"""
Get a structured dict of outputs of this recipe
:rtype dict
"""
return self.recipe_settings.get('outputs')
def get_recipe_params(self):
"""
Get the parameters of this recipe, as a dict
:rtype dict
"""
return self.recipe_settings.get('params')
def get_payload(self):
"""
Get the payload or script of this recipe, as a string
:rtype string
"""
self._payload_to_str()
return self._str_payload
def get_json_payload(self):
"""
Get the payload or script of this recipe, parsed from JSON, as a dict
:rtype dict
"""
self._payload_to_obj()
return self._obj_payload
def set_payload(self, payload):
"""
Set the payload of this recipe
:param str payload: the payload, as a string
"""
self._str_payload = payload
self._obj_payload = None
def set_json_payload(self, payload):
"""
Set the payload of this recipe
:param dict payload: the payload, as a dict. The payload will be converted to a JSON string internally
"""
self._str_payload = None
self._obj_payload = payload
def has_input(self, input_ref):
"""Returns whether this recipe has a given ref as input"""
inputs = self.get_recipe_inputs()
for (input_role_name, input_role) in inputs.items():
for item in input_role.get("items", []):
if item.get("ref", None) == input_ref:
return True
return False
def has_output(self, output_ref):
"""Returns whether this recipe has a given ref as output"""
outputs = self.get_recipe_outputs()
for (output_role_name, output_role) in outputs.items():
for item in output_role.get("items", []):
if item.get("ref", None) == output_ref:
return True
return False
def replace_input(self, current_input_ref, new_input_ref):
"""Replaces an object reference as input of this recipe by another"""
inputs = self.get_recipe_inputs()
for (input_role_name, input_role) in inputs.items():
for item in input_role.get("items", []):
if item.get("ref", None) == current_input_ref:
item["ref"] = new_input_ref
def replace_output(self, current_output_ref, new_output_ref):
"""Replaces an object reference as output of this recipe by another"""
outputs = self.get_recipe_outputs()
for (output_role_name, output_role) in outputs.items():
for item in output_role.get("items", []):
if item.get("ref", None) == current_output_ref:
item["ref"] = new_output_ref
def add_input(self, role, ref, partition_deps=None):
if partition_deps is None:
partition_deps = []
self._get_or_create_input_role(role)["items"].append({"ref": ref, "deps": partition_deps})
def add_output(self, role, ref, append_mode=False):
self._get_or_create_output_role(role)["items"].append({"ref": ref, "appendMode": append_mode})
def _get_or_create_input_role(self, role):
inputs = self.get_recipe_inputs()
if not role in inputs:
role_obj = {"items": []}
inputs[role] = role_obj
return inputs[role]
def _get_or_create_output_role(self, role):
outputs = self.get_recipe_outputs()
if not role in outputs:
role_obj = {"items": []}
outputs[role] = role_obj
return outputs[role]
def _get_flat_inputs(self):
ret = []
for role_key, role_obj in self.get_recipe_inputs().items():
for item in role_obj["items"]:
ret.append((role_key, item))
return ret
def _get_flat_outputs(self):
ret = []
for role_key, role_obj in self.get_recipe_outputs().items():
for item in role_obj["items"]:
ret.append((role_key, item))
return ret
def get_flat_input_refs(self):
"""
Returns a list of all input refs of this recipe, regardless of the input role
:rtype list of strings
"""
ret = []
for role_key, role_obj in self.get_recipe_inputs().items():
for item in role_obj["items"]:
ret.append(item["ref"])
return ret
def get_flat_output_refs(self):
"""
Returns a list of all output refs of this recipe, regardless of the output role
:rtype list of strings
"""
ret = []
for role_key, role_obj in self.get_recipe_outputs().items():
for item in role_obj["items"]:
ret.append(item["ref"])
return ret
# Old name, deprecated
class DSSRecipeDefinitionAndPayload(DSSRecipeSettings):
"""
Deprecated. Settings of a recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
pass
class RequiredSchemaUpdates(object):
"""
Representation of the updates required to the schema of the outputs of a recipe.
Do not create this class directly, use :meth:`DSSRecipe.compute_schema_updates`
"""
def __init__(self, recipe, data):
self.recipe = recipe
self.data = data
self.drop_and_recreate = True
self.synchronize_metastore = True
def any_action_required(self):
return self.data["totalIncompatibilities"] > 0
def apply(self):
results = []
for computable in self.data["computables"]:
osu = {
"computableType": computable["type"],
# dirty
"computableId": computable["type"] == "DATASET" and computable["datasetName"] or computable["id"],
"newSchema": computable["newSchema"],
"dropAndRecreate": self.drop_and_recreate,
"synchronizeMetastore" : self.synchronize_metastore
}
results.append(self.recipe.client._perform_json("POST",
"/projects/%s/recipes/%s/actions/updateOutputSchema" % (self.recipe.project_key, self.recipe.recipe_name),
body=osu))
return results
#####################################################
# Recipes creation infrastructure
#####################################################
class DSSRecipeCreator(object):
"""
Helper to create new recipes
:param str type: type of the recipe
:param str name: name for the recipe
:param :class:`dataikuapi.dss.project.DSSProject` project: project in which the recipe will be created
"""
def __init__(self, type, name, project):
self.project = project
self.recipe_proto = {
"inputs" : {},
"outputs" : {},
"type" : type,
"name" : name
}
self.creation_settings = {
}
def set_name(self, name):
self.recipe_proto["name"] = name
def _build_ref(self, object_id, project_key=None):
if project_key is not None and project_key != self.project.project_key:
return project_key + '.' + object_id
else:
return object_id
def _with_input(self, dataset_name, project_key=None, role="main"):
role_obj = self.recipe_proto["inputs"].get(role, None)
if role_obj is None:
role_obj = { "items" : [] }
self.recipe_proto["inputs"][role] = role_obj
role_obj["items"].append({'ref':self._build_ref(dataset_name, project_key)})
return self
def _with_output(self, dataset_name, append=False, role="main"):
role_obj = self.recipe_proto["outputs"].get(role, None)
if role_obj is None:
role_obj = { "items" : [] }
self.recipe_proto["outputs"][role] = role_obj
role_obj["items"].append({'ref':self._build_ref(dataset_name, None), 'appendMode': append})
return self
def _get_input_refs(self):
ret = []
for role_key, role_obj in self.recipe_proto["inputs"].items():
for item in role_obj["items"]:
ret.append(item["ref"])
return ret
def with_input(self, dataset_name, project_key=None, role="main"):
"""
Add an existing object as input to the recipe-to-be-created
:param dataset_name: name of the dataset, or identifier of the managed folder
or identifier of the saved model
:param project_key: project containing the object, if different from the one where the recipe is created
:param str role: the role of the recipe in which the input should be added
"""
return self._with_input(dataset_name, project_key, role)
def with_output(self, dataset_name, append=False, role="main"):
"""
The output dataset must already exist. If you are creating a visual recipe with a single
output, use with_existing_output
:param dataset_name: name of the dataset, or identifier of the managed folder
or identifier of the saved model
:param append: whether the recipe should append or overwrite the output when running
(note: not available for all dataset types)
:param str role: the role of the recipe in which the input should be added
"""
return self._with_output(dataset_name, append, role)
def build(self):
"""Deprecated. Use create()"""
return self.create()
def create(self):
"""
Creates the new recipe in the project, and return a handle to interact with it.
Returns:
A :class:`dataikuapi.dss.recipe.DSSRecipe` recipe handle
"""
self._finish_creation_settings()
return self.project.create_recipe(self.recipe_proto, self.creation_settings)
def set_raw_mode(self):
self.creation_settings["rawCreation"] = True
def _finish_creation_settings(self):
pass
class SingleOutputRecipeCreator(DSSRecipeCreator):
"""
Create a recipe that has a single output
"""
def __init__(self, type, name, project):
DSSRecipeCreator.__init__(self, type, name, project)
self.create_output_dataset = None
self.output_dataset_settings = None
self.create_output_folder = None
self.output_folder_settings = None
def with_existing_output(self, dataset_name, append=False, role="main"):
"""
Add an existing object as output to the recipe-to-be-created
:param dataset_name: name of the dataset, or identifier of the managed folder
or identifier of the saved model
:param append: whether the recipe should append or overwrite the output when running
(note: not available for all dataset types)
"""
assert self.create_output_dataset is None
self.create_output_dataset = False
self._with_output(dataset_name, append, role=role)
return self
def with_new_output(self, name, connection_id, typeOptionId=None, format_option_id=None, override_sql_schema=None, partitioning_option_id=None, append=False, object_type='DATASET', overwrite=False):
"""
Create a new dataset as output to the recipe-to-be-created. The dataset is not created immediately,
but when the recipe is created (ie in the create() method)
:param str name: name of the dataset or identifier of the managed folder
:param str connection_id: name of the connection to create the dataset on
:param str typeOptionId: sub-type of dataset, for connection where the type could be ambiguous. Typically,
this is SCP or SFTP, for SSH connection
:param str format_option_id: name of a format preset relevant for the dataset type. Possible values are: CSV_ESCAPING_NOGZIP_FORHIVE,
CSV_UNIX_GZIP, CSV_EXCEL_GZIP, CSV_EXCEL_GZIP_BIGQUERY, CSV_NOQUOTING_NOGZIP_FORPIG, PARQUET_HIVE,
AVRO, ORC
:param override_sql_schema: schema to force dataset, for SQL dataset. If left empty, will be autodetected
:param str partitioning_option_id: to copy the partitioning schema of an existing dataset 'foo', pass a
value of 'copy:dataset:foo'
:param append: whether the recipe should append or overwrite the output when running
(note: not available for all dataset types)
:param str object_type: DATASET or MANAGED_FOLDER
:param overwrite: If the dataset being created already exists, overwrite it (and delete data)
"""
if object_type == 'DATASET':
assert self.create_output_dataset is None
dataset = self.project.get_dataset(name)
if overwrite and dataset.exists():
dataset.delete(drop_data=True)
self.create_output_dataset = True
self.output_dataset_settings = {'connectionId':connection_id,'typeOptionId':typeOptionId,'specificSettings':{'formatOptionId':format_option_id, 'overrideSQLSchema':override_sql_schema},'partitioningOptionId':partitioning_option_id}
self._with_output(name, append)
elif object_type == 'MANAGED_FOLDER':
assert self.create_output_folder is None
self.create_output_folder = True
self.output_folder_settings = {'connectionId':connection_id,'typeOptionId':typeOptionId,'partitioningOptionId':partitioning_option_id}
self._with_output(name, append)
return self
def with_output(self, dataset_name, append=False, role="main"):
"""Alias of with_existing_output"""
return self.with_existing_output(dataset_name, append, role=role)
def _finish_creation_settings(self):
self.creation_settings['createOutputDataset'] = self.create_output_dataset
self.creation_settings['outputDatasetSettings'] = self.output_dataset_settings
self.creation_settings['createOutputFolder'] = self.create_output_folder
self.creation_settings['outputFolderSettings'] = self.output_folder_settings
class VirtualInputsSingleOutputRecipeCreator(SingleOutputRecipeCreator):
"""
Create a recipe that has a single output and several inputs
"""
def __init__(self, type, name, project):
SingleOutputRecipeCreator.__init__(self, type, name, project)
self.virtual_inputs = []
def with_input(self, dataset_name, project_key=None):
self.virtual_inputs.append(self._build_ref(dataset_name, project_key))
return self
def _finish_creation_settings(self):
super(VirtualInputsSingleOutputRecipeCreator, self)._finish_creation_settings()
self.creation_settings['virtualInputs'] = self.virtual_inputs
#####################################################
# Per-recipe-type classes: Visual recipes
#####################################################
class GroupingRecipeSettings(DSSRecipeSettings):
"""
Settings of a grouping recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
def clear_grouping_keys(self):
"""Removes all grouping keys from this grouping recipe"""
self.obj_payload["keys"] = []
def add_grouping_key(self, column):
"""
Adds grouping on a column
:param str column: Column to group on
"""
self.obj_payload["keys"].append({"column":column})
def set_global_count_enabled(self, enabled):
self.obj_payload["globalCount"] = enabled
def get_or_create_column_settings(self, column):
"""
Gets a dict representing the aggregations to perform on a column.
Creates it and adds it to the potential aggregations if it does not already exists
:param str column: The column name
:rtype dict
"""
found = None
for gv in self.obj_payload["values"]:
if gv["column"] == column:
found = gv
break
if found is None:
found = {"column" : column}
self.obj_payload["values"].append(found)
return found
def set_column_aggregations(self, column, type, min=False, max=False, count=False, count_distinct=False,
sum=False,concat=False,stddev=False,avg=False):
"""
Sets the basic aggregations on a column.
Returns the dict representing the aggregations on the column
:param str column: The column name
:param str type: The type of the column (as a DSS schema type name)
:rtype dict
"""
cs = self.get_or_create_column_settings(column)
cs["type"] = type
cs["min"] = min
cs["max"] = max
cs["count"] = count
cs["countDistinct"] = count_distinct
cs["sum"] = sum
cs["concat"] = concat
cs["stddev"] = stddev
return cs
class GroupingRecipeCreator(SingleOutputRecipeCreator):
"""
Create a Group recipe
"""
def __init__(self, name, project):
SingleOutputRecipeCreator.__init__(self, 'grouping', name, project)
self.group_key = None
def with_group_key(self, group_key):
"""
Set a column as the first grouping key. Only a single grouping key may be set
at recipe creation time. For additional groupings, get the recipe settings
:param str group_key: name of a column in the input dataset
"""
self.group_key = group_key
return self
def _finish_creation_settings(self):
super(GroupingRecipeCreator, self)._finish_creation_settings()
if self.group_key is not None:
self.creation_settings['groupKey'] = self.group_key
class WindowRecipeSettings(DSSRecipeSettings):
"""
Settings of a window recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
pass # TODO: Write helpers for window
class WindowRecipeCreator(SingleOutputRecipeCreator):
"""
Create a Window recipe
"""
def __init__(self, name, project):
SingleOutputRecipeCreator.__init__(self, 'window', name, project)
class SyncRecipeSettings(DSSRecipeSettings):
"""
Settings of a sync recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
pass # TODO: Write helpers for sync
class SyncRecipeCreator(SingleOutputRecipeCreator):
"""
Create a Sync recipe
"""
def __init__(self, name, project):
SingleOutputRecipeCreator.__init__(self, 'sync', name, project)
class SortRecipeSettings(DSSRecipeSettings):
"""
Settings of a sort recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
pass # TODO: Write helpers for sort
class SortRecipeCreator(SingleOutputRecipeCreator):
"""
Create a Sort recipe
"""
def __init__(self, name, project):
SingleOutputRecipeCreator.__init__(self, 'sort', name, project)
class TopNRecipeSettings(DSSRecipeSettings):
"""
Settings of a topn recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
pass # TODO: Write helpers for topn
class TopNRecipeCreator(DSSRecipeCreator):
"""
Create a TopN recipe
"""
def __init__(self, name, project):
DSSRecipeCreator.__init__(self, 'topn', name, project)
class DistinctRecipeSettings(DSSRecipeSettings):
"""
Settings of a distinct recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
pass # TODO: Write helpers for distinct
class DistinctRecipeCreator(SingleOutputRecipeCreator):
"""
Create a Distinct recipe
"""
def __init__(self, name, project):
SingleOutputRecipeCreator.__init__(self, 'distinct', name, project)
class PrepareRecipeSettings(DSSRecipeSettings):
"""
Settings of a prepare recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
"""
pass
@property
def raw_steps(self):
"""
Returns a raw list of the steps of this prepare recipe.
You can modify the returned list.
Each step is a dict of settings. The precise settings for each step are not documented
"""
return self.obj_payload["steps"]
def add_processor_step(self, type, params):
step = {
"metaType": "PROCESSOR",
"type": type,
"params": params
}
self.raw_steps.append(step)
def add_filter_on_bad_meaning(self, meaning, columns):
params = {
"action" : "REMOVE_ROW",
"type" : meaning
}
if isinstance(columns, basestring):
params["appliesTo"] = "SINGLE_COLUMN"
params["columns"] = [columns]
elif isinstance(columns, list):
params["appliesTo"] = "COLUMNS"
params["columns"] = columns
class PrepareRecipeCreator(SingleOutputRecipeCreator):
"""
Create a Prepare recipe
"""
def __init__(self, name, project):
SingleOutputRecipeCreator.__init__(self, 'shaker', name, project)
class JoinRecipeSettings(DSSRecipeSettings):
"""
Settings of a join recipe. Do not create this directly, use :meth:`DSSRecipe.get_settings`
In order to enable self-joins, join recipes are based on a concept of "virtual inputs".
Every join, computed pre-join column, pre-join filter, ... is based on one virtual input, and
each virtual input references an input of the recipe, by index
For example, if a recipe has inputs A and B and declares two joins:
- A->B
- A->A(based on a computed column)
There are 3 virtual inputs:
* 0: points to recipe input 0 (i.e. dataset A)
* 1: points to recipe input 1 (i.e. dataset B)
* 2: points to recipe input 0 (i.e. dataset A) and includes the computed column
* The first join is between virtual inputs 0 and 1
* The second join is between virtual inputs 0 and 2
"""
pass # TODO: Write helpers for join
@property
def raw_virtual_inputs(self):
"""
Returns the raw list of virtual inputs
:rtype list of dict
"""
return self.obj_payload["virtualInputs"]
@property
def raw_joins(self):
"""
Returns the raw list of joins
:rtype list of dict
"""
return self.obj_payload["joins"]
def add_virtual_input(self, input_dataset_index):
"""
Adds a virtual input pointing to the specified input dataset of the recipe
(referenced by index in the inputs list)
"""
self.raw_virtual_inputs.append({"index": input_dataset_index})
def add_pre_join_computed_column(self, virtual_input_index, computed_column):
"""
Adds a computed column to a virtual input
Use :class:`dataikuapi.dss.utils.DSSComputedColumn` to build the computed_column object
"""
self.raw_virtual_inputs[virtual_input_index]["computedColumns"].append(computed_column)
def add_join(self, join_type="LEFT", input1=0, input2=1):
"""
Adds a join between two virtual inputs. The join is initialized with no condition.
Use :meth:`add_condition_to_join` on the return value to add a join condition (for example column equality)
to the join
:returns the newly added join as a dict
:rtype dict
"""