-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCardinality.ecl
398 lines (366 loc) · 18.1 KB
/
Cardinality.ecl
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
/***
* Function macro for computing the cardinality of values within all or part
* of a dataset. The output is a dataset containing the following information
* for each processed attribute:
*
* attribute The name of the field
* value A value from the field as a UTF-8 string
* rec_count The number of records analyzed in the dataset
* that contained that particular value
*
* The result will be returned sorted by (attribute, -rec_count, value).
*
* The result from this function macro can be considered an expanded or more
* complete version of what is found in the 'cardinality_breakdown' result from
* DataPatterns.Profile(). Here, there is no limit on the number of unique
* values that will be captured. Also, as can be seen from the return structure
* outlined above, the result is a simple three-field dataset (no child datasets
* to process).
*
* Function parameters:
*
* @param inFile The dataset to process; this could be a child
* dataset (e.g. inFile.childDS); REQUIRED
* @param fieldListStr A string containing a comma-delimited list of
* attribute names to process; use an empty string to
* process all attributes in inFile; OPTIONAL,
* defaults to an empty string
* @param sampleSize A positive integer representing a percentage of
* inFile to examine, which is useful when analyzing a
* very large dataset and only an estimated cardinality
* is sufficient; valid range for this argument is 1-100;
* values outside of this range will be clamped; OPTIONAL,
* defaults to 100 (which indicates that the entire dataset
* will be analyzed)
*/
EXPORT Cardinality(inFile,
fieldListStr = '\'\'',
sampleSize = 100) := FUNCTIONMACRO
LOADXML('<xml/>');
#UNIQUENAME(temp); // Ubiquitous "contains random things"
#UNIQUENAME(scalarFields); // Contains a delimited list of scalar attributes (full names) along with their indexed positions
#UNIQUENAME(explicitScalarFields); // Contains a delimited list of scalar attributes (full names) without indexed positions
#UNIQUENAME(childDSFields); // Contains a delimited list of child dataset attributes (full names) along with their indexed positions
#UNIQUENAME(fieldCount); // Contains the number of fields we've seen while processing record layouts
#UNIQUENAME(recLevel); // Will be used to determine at which level we are processing
#UNIQUENAME(fieldStack); // String-based stack telling us whether we're within an embedded dataset or record
#UNIQUENAME(namePrefix); // When processing child records and datasets, contains the leading portion of the attribute's full name
#UNIQUENAME(fullName); // The full name of an attribute
#UNIQUENAME(needsDelim); // Boolean indicating whether we need to insert a delimiter somewhere
#UNIQUENAME(namePos); // Contains character offset information, for parsing delimited strings
#UNIQUENAME(namePos2); // Contains character offset information, for parsing delimited strings
#UNIQUENAME(nameValue); // Extracted string value from a string
#UNIQUENAME(nameValue2); // Extracted string value from a string
IMPORT Std;
//--------------------------------------------------------------------------
// Remove all spaces from field list so we can parse it more easily
#UNIQUENAME(trimmedFieldList);
LOCAL %trimmedFieldList% := TRIM((STRING)fieldListStr, ALL);
// Typedefs
#UNIQUENAME(Attribute_t);
LOCAL %Attribute_t% := STRING;
#UNIQUENAME(AttributeValue_t);
LOCAL %AttributeValue_t% := UTF8;
#UNIQUENAME(RecordCount_t);
LOCAL %RecordCount_t% := UNSIGNED8;
//--------------------------------------------------------------------------
// Ungroup the given dataset, in case it was grouped
#UNIQUENAME(ungroupedInFile);
LOCAL %ungroupedInFile% := UNGROUP(inFile);
// Clamp the sample size to something reasonable
#UNIQUENAME(clampedSampleSize);
LOCAL %clampedSampleSize% := MAX(1, MIN(100, (INTEGER)sampleSize));
// Create a sample dataset if needed
#UNIQUENAME(sampledData);
LOCAL %sampledData% := IF
(
%clampedSampleSize% < 100,
ENTH(%ungroupedInFile%, %clampedSampleSize%, 100, 1, LOCAL),
%ungroupedInFile%
);
// Slim the dataset if the caller provided an explicit set of attributes;
// note that explicit attributes within a top-level child dataset will
// cause the entire top-level child dataset to be retained
#UNIQUENAME(workingInFile);
LOCAL %workingInFile% :=
#IF(%trimmedFieldList% = '')
%sampledData%
#ELSE
TABLE
(
%sampledData%,
{
#SET(needsDelim, 0)
#SET(namePos, 1)
#SET(nameValue2, '')
#LOOP
#SET(temp, REGEXFIND('^([^,]+)', %trimmedFieldList%[%namePos%..], 1))
#IF(%'temp'% != '')
#SET(nameValue, REGEXFIND('^([^\\.]+)', %'temp'%, 1))
#IF(NOT REGEXFIND('\\b' + %'nameValue'% + '\\b', %'nameValue2'%))
#IF(%'nameValue2'% != '')
#APPEND(nameValue2, ',')
#END
#APPEND(nameValue2, %'nameValue'%)
#IF(%needsDelim% = 1) , #END
TYPEOF(%sampledData%.%nameValue%) %nameValue% := %nameValue%
#SET(needsDelim, 1)
#END
#SET(namePos, %namePos% + LENGTH(%'temp'%) + 1)
#ELSE
#BREAK
#END
#END
}
)
#END;
// Distribute the inbound dataset across all our nodes for faster processing
#UNIQUENAME(distributedInFile);
LOCAL %distributedInFile% := DISTRIBUTE(%workingInFile%, SKEW(0.05));
#EXPORTXML(inFileFields, RECORDOF(%distributedInFile%));
// Walk the slimmed dataset, pulling out top-level scalars and noting
// child datasets
#SET(scalarFields, '');
#SET(childDSFields, '');
#SET(fieldCount, 0);
#SET(recLevel, 0);
#SET(fieldStack, '');
#SET(namePrefix, '');
#SET(fullName, '');
#FOR(inFileFields)
#FOR(Field)
#SET(fieldCount, %fieldCount% + 1)
#IF(%{@isEnd}% != 1)
// Adjust full name
#SET(fullName, %'namePrefix'% + %'@name'%)
#END
#IF(%{@isRecord}% = 1)
// Push record onto stack so we know what we're popping when we see @isEnd
#SET(fieldStack, 'r' + %'fieldStack'%)
#APPEND(namePrefix, %'@name'% + '.')
#ELSEIF(%{@isDataset}% = 1)
// Push dataset onto stack so we know what we're popping when we see @isEnd
#SET(fieldStack, 'd' + %'fieldStack'%)
#APPEND(namePrefix, %'@name'% + '.')
#SET(recLevel, %recLevel% + 1)
// Note the field index and field name so we can process it separately
#IF(%'childDSFields'% != '')
#APPEND(childDSFields, ',')
#END
#APPEND(childDSFields, %'fieldCount'% + ':' + %'fullName'%)
// Extract the child dataset into its own attribute so we can more easily
// process it later
#SET(temp, #MANGLE(%'fullName'%));
LOCAL %temp% := NORMALIZE
(
%distributedInFile%,
LEFT.%fullName%,
TRANSFORM
(
RECORDOF(%distributedInFile%.%fullName%),
SELF := RIGHT
)
);
#ELSEIF(%{@isEnd}% = 1)
#SET(namePrefix, REGEXREPLACE('\\w+\\.$', %'namePrefix'%, ''))
#IF(%'fieldStack'%[1] = 'd')
#SET(recLevel, %recLevel% - 1)
#END
#SET(fieldStack, %'fieldStack'%[2..])
#ELSEIF(%recLevel% = 0)
// Note the field index and full name of the attribute so we can process it
#IF(%'scalarFields'% != '')
#APPEND(scalarFields, ',')
#END
#APPEND(scalarFields, %'fieldCount'% + ':' + %'fullName'%)
#END
#END
#END
// Collect the gathered full attribute names so we can walk them later
#SET(explicitScalarFields, REGEXREPLACE('\\d+:', %'scalarFields'%, ''));
// Define the record layout that will be used by the inner _Inner_Cardinality() call
LOCAL OutputLayout := RECORD
%Attribute_t% attribute;
%AttributeValue_t% value;
%RecordCount_t% rec_count;
END;
//==========================================================================
// This is the meat of the function macro that actually does the work;
// it is called with various datasets and (possibly) explicit attributes
// to process and the results will eventually be combined to form the
// final result; the parameters largely match the Cardinality() call, with the
// addition of a few parameters that help place the results into the
// correct format; note that the name of this function macro is not wrapped
// in a UNIQUENAME -- that is due to an apparent limitation in the ECL
// compiler
LOCAL _Inner_Cardinality(_inFile,
_fieldListStr,
_resultLayout,
_attrNamePrefix) := FUNCTIONMACRO
#EXPORTXML(inFileFields, RECORDOF(_inFile));
#UNIQUENAME(explicitFields);
// Validate that attribute is okay for us to process (there is no explicit
// attribute list or the name is in the list)
#UNIQUENAME(_CanProcessAttribute);
LOCAL %_CanProcessAttribute%(STRING attrName) := (_fieldListStr = '' OR REGEXFIND('(^|,)' + attrName + '(,|$)', _fieldListStr, NOCASE));
// Collect a list of the top-level attributes that we can process
#SET(needsDelim, 0);
#SET(recLevel, 0);
#SET(fieldStack, '');
#SET(namePrefix, '');
#SET(explicitFields, '');
#FOR(inFileFields)
#FOR(Field)
#IF(%{@isRecord}% = 1)
#SET(fieldStack, 'r' + %'fieldStack'%)
#APPEND(namePrefix, %'@name'% + '.')
#ELSEIF(%{@isDataset}% = 1)
#SET(fieldStack, 'd' + %'fieldStack'%)
#SET(recLevel, %recLevel% + 1)
#ELSEIF(%{@isEnd}% = 1)
#IF(%'fieldStack'%[1] = 'd')
#SET(recLevel, %recLevel% - 1)
#ELSE
#SET(namePrefix, REGEXREPLACE('\\w+\\.$', %'namePrefix'%, ''))
#END
#SET(fieldStack, %'fieldStack'%[2..])
#ELSEIF(%recLevel% = 0)
#IF(%_CanProcessAttribute%(%'namePrefix'% + %'@name'%))
#IF(%needsDelim% = 1)
#APPEND(explicitFields, ',')
#END
#APPEND(explicitFields, %'namePrefix'% + %'@name'%)
#SET(needsDelim, 1)
#END
#END
#END
#END
#UNIQUENAME(dataInfo);
LOCAL %dataInfo% :=
#SET(recLevel, 0)
#SET(fieldStack, '')
#SET(namePrefix, '')
#SET(needsDelim, 0)
#SET(fieldCount, 0)
#FOR(inFileFields)
#FOR(Field)
#IF(%{@isRecord}% = 1)
#SET(fieldStack, 'r' + %'fieldStack'%)
#APPEND(namePrefix, %'@name'% + '.')
#ELSEIF(%{@isDataset}% = 1)
#SET(fieldStack, 'd' + %'fieldStack'%)
#SET(recLevel, %recLevel% + 1)
#ELSEIF(%{@isEnd}% = 1)
#IF(%'fieldStack'%[1] = 'd')
#SET(recLevel, %recLevel% - 1)
#ELSE
#SET(namePrefix, REGEXREPLACE('\\w+\\.$', %'namePrefix'%, ''))
#END
#SET(fieldStack, %'fieldStack'%[2..])
#ELSEIF(%recLevel% = 0)
#IF(%_CanProcessAttribute%(%'namePrefix'% + %'@name'%))
#SET(fieldCount, %fieldCount% + 1)
#IF(%needsDelim% = 1) + #END
IF(EXISTS(_inFile),
PROJECT
(
TABLE
(
_inFile,
{
%Attribute_t% attribute := _attrNamePrefix + %'namePrefix'% + %'@name'%,
%AttributeValue_t% value := (%AttributeValue_t%)_inFile.#EXPAND(%'namePrefix'% + %'@name'%),
%RecordCount_t% rec_count := COUNT(GROUP)
},
_inFile.#EXPAND(%'namePrefix'% + %'@name'%),
MERGE
),
TRANSFORM(_resultLayout, SELF := LEFT)
),
DATASET
(
1,
TRANSFORM
(
_resultLayout,
SELF.attribute := _attrNamePrefix + %'namePrefix'% + %'@name'%,
SELF.value := (%AttributeValue_t%)'',
SELF := []
)
)
)
#SET(needsDelim, 1)
#END
#END
#END
#END
// Insert empty value for syntax checking
#IF(%fieldCount% = 0)
DATASET([], _resultLayout)
#END;
RETURN #IF(%fieldCount% > 0) %dataInfo% #ELSE DATASET([], _resultLayout) #END;
ENDMACRO;
//==========================================================================
// Call _Inner_Cardinality() with the given input dataset top-level scalar attributes,
// then again for each child dataset that has been found; combine the
// results of all the calls
#UNIQUENAME(collectedResults);
LOCAL %collectedResults% :=
#IF(%'explicitScalarFields'% != '')
_Inner_Cardinality
(
GLOBAL(%distributedInFile%),
%'explicitScalarFields'%,
OutputLayout,
''
)
#ELSE
DATASET([], OutputLayout)
#END
#UNIQUENAME(dsNameValue)
#SET(namePos, 1)
#LOOP
#SET(dsNameValue, REGEXFIND('^([^,]+)', %'childDSFields'%[%namePos%..], 1))
#IF(%'dsNameValue'% != '')
#SET(nameValue, REGEXFIND(':([^:]+)$', %'dsNameValue'%, 1))
// Extract a list of fields within this child dataset if necessary
#SET(explicitScalarFields, '')
#SET(needsDelim, 0)
#SET(namePos2, 1)
#LOOP
#SET(temp, REGEXFIND('^([^,]+)', %trimmedFieldList%[%namePos2%..], 1))
#IF(%'temp'% != '')
#SET(nameValue2, REGEXFIND('^' + %'nameValue'% + '\\.([^,]+)', %'temp'%, 1))
#IF(%'nameValue2'% != '')
#IF(%needsDelim% = 1)
#APPEND(explicitScalarFields, ',')
#END
#APPEND(explicitScalarFields, %'nameValue2'%)
#SET(needsDelim, 1)
#END
#SET(namePos2, %namePos2% + LENGTH(%'temp'%) + 1)
#ELSE
#BREAK
#END
#END
// The child dataset should have been extracted into its own
// local attribute; reference it during our call to the inner
// cardinality function macro
#SET(temp, #MANGLE(%'nameValue'%))
+ _Inner_Cardinality
(
GLOBAL(%temp%),
%'explicitScalarFields'%,
OutputLayout,
%'nameValue'% + '.'
)
#SET(namePos, %namePos% + LENGTH(%'dsNameValue'%) + 1)
#ELSE
#BREAK
#END
#END;
// Put the combined _Inner_Cardinality() results in the right order and layout
#UNIQUENAME(finalData);
LOCAL %finalData% := PROJECT(SORT(%collectedResults%, attribute, -rec_count, value), OutputLayout);
RETURN %finalData%;
ENDMACRO;