forked from johnkerl/miller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uniq.go
603 lines (520 loc) · 18.2 KB
/
uniq.go
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
package transformers
import (
"container/list"
"fmt"
"os"
"strings"
"github.com/johnkerl/miller/internal/pkg/cli"
"github.com/johnkerl/miller/internal/pkg/lib"
"github.com/johnkerl/miller/internal/pkg/mlrval"
"github.com/johnkerl/miller/internal/pkg/types"
)
// ----------------------------------------------------------------
const verbNameCountDistinct = "count-distinct"
const verbNameUniq = "uniq"
const uniqDefaultOutputFieldName = "count"
var CountDistinctSetup = TransformerSetup{
Verb: verbNameCountDistinct,
UsageFunc: transformerCountDistinctUsage,
ParseCLIFunc: transformerCountDistinctParseCLI,
IgnoresInput: false,
}
var UniqSetup = TransformerSetup{
Verb: verbNameUniq,
UsageFunc: transformerUniqUsage,
ParseCLIFunc: transformerUniqParseCLI,
IgnoresInput: false,
}
// ----------------------------------------------------------------
func transformerCountDistinctUsage(
o *os.File,
) {
argv0 := "mlr"
verb := verbNameCountDistinct
fmt.Fprintf(o, "Usage: %s %s [options]\n", argv0, verb)
fmt.Fprintf(o, "Prints number of records having distinct values for specified field names.\n")
fmt.Fprintf(o, "Same as uniq -c.\n")
fmt.Fprintf(o, "\n")
fmt.Fprintf(o, "Options:\n")
fmt.Fprintf(o, "-f {a,b,c} Field names for distinct count.\n")
fmt.Fprintf(o, "-n Show only the number of distinct values. Not compatible with -u.\n")
fmt.Fprintf(o, "-o {name} Field name for output count. Default \"%s\".\n", uniqDefaultOutputFieldName)
fmt.Fprintf(o, " Ignored with -u.\n")
fmt.Fprintf(o, "-u Do unlashed counts for multiple field names. With -f a,b and\n")
fmt.Fprintf(o, " without -u, computes counts for distinct combinations of a\n")
fmt.Fprintf(o, " and b field values. With -f a,b and with -u, computes counts\n")
fmt.Fprintf(o, " for distinct a field values and counts for distinct b field\n")
fmt.Fprintf(o, " values separately.\n")
}
func transformerCountDistinctParseCLI(
pargi *int,
argc int,
args []string,
_ *cli.TOptions,
doConstruct bool, // false for first pass of CLI-parse, true for second pass
) IRecordTransformer {
// Skip the verb name from the current spot in the mlr command line
argi := *pargi
verb := args[argi]
argi++
// Parse local flags
var fieldNames []string = nil
showNumDistinctOnly := false
outputFieldName := uniqDefaultOutputFieldName
doLashed := true
for argi < argc /* variable increment: 1 or 2 depending on flag */ {
opt := args[argi]
if !strings.HasPrefix(opt, "-") {
break // No more flag options to process
}
if args[argi] == "--" {
break // All transformers must do this so main-flags can follow verb-flags
}
argi++
if opt == "-h" || opt == "--help" {
transformerCountDistinctUsage(os.Stdout)
os.Exit(0)
} else if opt == "-g" || opt == "-f" {
fieldNames = cli.VerbGetStringArrayArgOrDie(verb, opt, args, &argi, argc)
} else if opt == "-n" {
showNumDistinctOnly = true
} else if opt == "-o" {
outputFieldName = cli.VerbGetStringArgOrDie(verb, opt, args, &argi, argc)
} else if opt == "-u" {
doLashed = false
} else {
transformerCountDistinctUsage(os.Stderr)
os.Exit(1)
}
}
if fieldNames == nil {
transformerCountDistinctUsage(os.Stderr)
os.Exit(1)
}
if !doLashed && showNumDistinctOnly {
transformerCountDistinctUsage(os.Stderr)
os.Exit(1)
}
showCounts := true
uniqifyEntireRecords := false
*pargi = argi
if !doConstruct { // All transformers must do this for main command-line parsing
return nil
}
transformer, err := NewTransformerUniq(
fieldNames,
showCounts,
showNumDistinctOnly,
outputFieldName,
doLashed,
uniqifyEntireRecords,
)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return transformer
}
// ----------------------------------------------------------------
func transformerUniqUsage(
o *os.File,
) {
argv0 := "mlr"
verb := verbNameUniq
fmt.Fprintf(o, "Usage: %s %s [options]\n", argv0, verb)
fmt.Fprintf(o, "Prints distinct values for specified field names. With -c, same as\n")
fmt.Fprintf(o, "count-distinct. For uniq, -f is a synonym for -g.\n")
fmt.Fprintf(o, "\n")
fmt.Fprintf(o, "Options:\n")
fmt.Fprintf(o, "-g {d,e,f} Group-by-field names for uniq counts.\n")
fmt.Fprintf(o, "-c Show repeat counts in addition to unique values.\n")
fmt.Fprintf(o, "-n Show only the number of distinct values.\n")
fmt.Fprintf(o, "-o {name} Field name for output count. Default \"%s\".\n", uniqDefaultOutputFieldName)
fmt.Fprintf(o, "-a Output each unique record only once. Incompatible with -g.\n")
fmt.Fprintf(o, " With -c, produces unique records, with repeat counts for each.\n")
fmt.Fprintf(o, " With -n, produces only one record which is the unique-record count.\n")
fmt.Fprintf(o, " With neither -c nor -n, produces unique records.\n")
}
func transformerUniqParseCLI(
pargi *int,
argc int,
args []string,
_ *cli.TOptions,
doConstruct bool, // false for first pass of CLI-parse, true for second pass
) IRecordTransformer {
// Skip the verb name from the current spot in the mlr command line
argi := *pargi
verb := args[argi]
argi++
// Parse local flags
var fieldNames []string = nil
showCounts := false
showNumDistinctOnly := false
outputFieldName := uniqDefaultOutputFieldName
uniqifyEntireRecords := false
for argi < argc /* variable increment: 1 or 2 depending on flag */ {
opt := args[argi]
if !strings.HasPrefix(opt, "-") {
break // No more flag options to process
}
if args[argi] == "--" {
break // All transformers must do this so main-flags can follow verb-flags
}
argi++
if opt == "-h" || opt == "--help" {
transformerUniqUsage(os.Stdout)
os.Exit(0)
} else if opt == "-g" || opt == "-f" {
fieldNames = cli.VerbGetStringArrayArgOrDie(verb, opt, args, &argi, argc)
} else if opt == "-c" {
showCounts = true
} else if opt == "-n" {
showNumDistinctOnly = true
} else if opt == "-o" {
outputFieldName = cli.VerbGetStringArgOrDie(verb, opt, args, &argi, argc)
} else if opt == "-a" {
uniqifyEntireRecords = true
} else {
transformerUniqUsage(os.Stderr)
os.Exit(1)
}
}
if uniqifyEntireRecords {
if fieldNames != nil {
transformerUniqUsage(os.Stderr)
os.Exit(1)
}
if showCounts && showNumDistinctOnly {
transformerUniqUsage(os.Stderr)
os.Exit(1)
}
} else {
if fieldNames == nil {
transformerUniqUsage(os.Stderr)
os.Exit(1)
}
}
doLashed := true
*pargi = argi
if !doConstruct { // All transformers must do this for main command-line parsing
return nil
}
transformer, _ := NewTransformerUniq(
fieldNames,
showCounts,
showNumDistinctOnly,
outputFieldName,
doLashed,
uniqifyEntireRecords,
)
return transformer
}
// ----------------------------------------------------------------
type TransformerUniq struct {
fieldNames []string
showCounts bool
outputFieldName string
// Example:
// Input is:
// a=1,b=2,c=3
// a=4,b=5,c=6
// Uniquing on fields ["a","b"]
// uniqifiedRecordCounts:
// '{"a":1,"b":2,"c":3}' => 1
// '{"a":4,"b":5,"c":6}' => 1
// uniqifiedRecords:
// '{"a":1,"b":2,"c":3}' => {"a":1,"b":2,"c":3}
// '{"a":4,"b":5,"c":6}' => {"a":4,"b":5,"c":6}
// countsByGroup:
// "1,2" -> 1
// "4,5" -> 1
// valuesByGroup:
// "1,2" -> [1,2]
// "4,5" -> [4,5]
// unlashedCounts:
// "a" => "1" => 1
// "a" => "4" => 1
// ...
// unlashedCountValues:
// "a" => "1" => 1
// "a" => "4" => 4
uniqifiedRecordCounts *lib.OrderedMap // record-as-string -> counts
uniqifiedRecords *lib.OrderedMap // record-as-string -> records
countsByGroup *lib.OrderedMap // grouping key -> count
valuesByGroup *lib.OrderedMap // grouping key -> array of values
unlashedCounts *lib.OrderedMap // field name -> string field value -> count
unlashedCountValues *lib.OrderedMap // field name -> string field value -> typed field value
recordTransformerFunc RecordTransformerFunc
}
// ----------------------------------------------------------------
func NewTransformerUniq(
fieldNames []string,
showCounts bool,
showNumDistinctOnly bool,
outputFieldName string,
doLashed bool,
uniqifyEntireRecords bool,
) (*TransformerUniq, error) {
tr := &TransformerUniq{
fieldNames: fieldNames,
showCounts: showCounts,
outputFieldName: outputFieldName,
uniqifiedRecordCounts: lib.NewOrderedMap(),
uniqifiedRecords: lib.NewOrderedMap(),
countsByGroup: lib.NewOrderedMap(),
valuesByGroup: lib.NewOrderedMap(),
unlashedCounts: lib.NewOrderedMap(),
unlashedCountValues: lib.NewOrderedMap(),
}
if uniqifyEntireRecords {
if showCounts {
tr.recordTransformerFunc = tr.transformUniqifyEntireRecordsShowCounts
} else if showNumDistinctOnly {
tr.recordTransformerFunc = tr.transformUniqifyEntireRecordsShowNumDistinctOnly
} else {
tr.recordTransformerFunc = tr.transformUniqifyEntireRecords
}
} else if !doLashed {
tr.recordTransformerFunc = tr.transformUnlashed
} else if showNumDistinctOnly {
tr.recordTransformerFunc = tr.transformNumDistinctOnly
} else if showCounts {
tr.recordTransformerFunc = tr.transformWithCounts
} else {
tr.recordTransformerFunc = tr.transformWithoutCounts
}
return tr, nil
}
// ----------------------------------------------------------------
func (tr *TransformerUniq) Transform(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
HandleDefaultDownstreamDone(inputDownstreamDoneChannel, outputDownstreamDoneChannel)
tr.recordTransformerFunc(inrecAndContext, outputRecordsAndContexts, inputDownstreamDoneChannel, outputDownstreamDoneChannel)
}
// ----------------------------------------------------------------
// Print each unique record only once, with uniqueness counts. This means
// non-streaming, with output at end of stream.
func (tr *TransformerUniq) transformUniqifyEntireRecordsShowCounts(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
if !inrecAndContext.EndOfStream {
inrec := inrecAndContext.Record
recordAsString := inrec.String()
icount, present := tr.uniqifiedRecordCounts.GetWithCheck(recordAsString)
if !present { // first time seen
tr.uniqifiedRecordCounts.Put(recordAsString, int64(1))
tr.uniqifiedRecords.Put(recordAsString, inrecAndContext.Copy())
} else { // have seen before
tr.uniqifiedRecordCounts.Put(recordAsString, icount.(int64)+1)
}
} else { // end of record stream
for pe := tr.uniqifiedRecords.Head; pe != nil; pe = pe.Next {
outrecAndContext := pe.Value.(*types.RecordAndContext)
icount := tr.uniqifiedRecordCounts.Get(pe.Key)
mcount := mlrval.FromInt(icount.(int64))
outrecAndContext.Record.PrependReference(tr.outputFieldName, mcount)
outputRecordsAndContexts.PushBack(outrecAndContext)
}
outputRecordsAndContexts.PushBack(inrecAndContext) // end-of-stream marker
}
}
// ----------------------------------------------------------------
// Print count of unique records. This means non-streaming, with output at end
// of stream.
func (tr *TransformerUniq) transformUniqifyEntireRecordsShowNumDistinctOnly(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
if !inrecAndContext.EndOfStream {
inrec := inrecAndContext.Record
recordAsString := inrec.String()
if !tr.uniqifiedRecordCounts.Has(recordAsString) {
tr.uniqifiedRecordCounts.Put(recordAsString, int64(1))
}
} else { // end of record stream
outrec := mlrval.NewMlrmapAsRecord()
outrec.PutReference(
tr.outputFieldName,
mlrval.FromInt(tr.uniqifiedRecordCounts.FieldCount),
)
outputRecordsAndContexts.PushBack(types.NewRecordAndContext(outrec, &inrecAndContext.Context))
outputRecordsAndContexts.PushBack(inrecAndContext) // end-of-stream marker
}
}
// ----------------------------------------------------------------
// Print each unique record only once (on first occurrence).
func (tr *TransformerUniq) transformUniqifyEntireRecords(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
if !inrecAndContext.EndOfStream {
inrec := inrecAndContext.Record
recordAsString := inrec.String()
if !tr.uniqifiedRecordCounts.Has(recordAsString) {
tr.uniqifiedRecordCounts.Put(recordAsString, int64(1))
outputRecordsAndContexts.PushBack(inrecAndContext)
}
} else { // end of record stream
outputRecordsAndContexts.PushBack(inrecAndContext) // end-of-stream marker
}
}
// ----------------------------------------------------------------
func (tr *TransformerUniq) transformUnlashed(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
if !inrecAndContext.EndOfStream {
inrec := inrecAndContext.Record
for _, fieldName := range tr.fieldNames {
var countsForFieldName *lib.OrderedMap = nil
iCountsForFieldName, present := tr.unlashedCounts.GetWithCheck(fieldName)
if !present {
countsForFieldName = lib.NewOrderedMap()
tr.unlashedCounts.Put(fieldName, countsForFieldName)
tr.unlashedCountValues.Put(fieldName, lib.NewOrderedMap())
} else {
countsForFieldName = iCountsForFieldName.(*lib.OrderedMap)
}
fieldValue := inrec.Get(fieldName)
if fieldValue != nil {
fieldValueString := fieldValue.String()
if !countsForFieldName.Has(fieldValueString) {
countsForFieldName.Put(fieldValueString, int64(1))
tr.unlashedCountValues.Get(fieldName).(*lib.OrderedMap).Put(fieldValueString, fieldValue.Copy())
} else {
countsForFieldName.Put(fieldValueString, countsForFieldName.Get(fieldValueString).(int64)+1)
}
}
}
} else { // end of record stream
for pe := tr.unlashedCounts.Head; pe != nil; pe = pe.Next {
fieldName := pe.Key
countsForFieldName := pe.Value.(*lib.OrderedMap)
for pf := countsForFieldName.Head; pf != nil; pf = pf.Next {
fieldValueString := pf.Key
outrec := mlrval.NewMlrmapAsRecord()
outrec.PutReference("field", mlrval.FromString(fieldName))
outrec.PutCopy(
"value",
tr.unlashedCountValues.Get(fieldName).(*lib.OrderedMap).Get(fieldValueString).(*mlrval.Mlrval),
)
outrec.PutReference("count", mlrval.FromInt(pf.Value.(int64)))
outputRecordsAndContexts.PushBack(types.NewRecordAndContext(outrec, &inrecAndContext.Context))
}
}
outputRecordsAndContexts.PushBack(inrecAndContext) // end-of-stream marker
}
}
// ----------------------------------------------------------------
func (tr *TransformerUniq) transformNumDistinctOnly(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
if !inrecAndContext.EndOfStream {
inrec := inrecAndContext.Record
groupingKey, ok := inrec.GetSelectedValuesJoined(tr.fieldNames)
if ok {
iCount, present := tr.countsByGroup.GetWithCheck(groupingKey)
if !present {
tr.countsByGroup.Put(groupingKey, int64(1))
} else {
tr.countsByGroup.Put(groupingKey, iCount.(int64)+1)
}
}
} else {
outrec := mlrval.NewMlrmapAsRecord()
outrec.PutReference(
"count",
mlrval.FromInt(tr.countsByGroup.FieldCount),
)
outputRecordsAndContexts.PushBack(types.NewRecordAndContext(outrec, &inrecAndContext.Context))
outputRecordsAndContexts.PushBack(inrecAndContext) // end-of-stream marker
}
}
// ----------------------------------------------------------------
func (tr *TransformerUniq) transformWithCounts(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
if !inrecAndContext.EndOfStream {
inrec := inrecAndContext.Record
groupingKey, selectedValues, ok := inrec.GetSelectedValuesAndJoined(tr.fieldNames)
if ok {
iCount, present := tr.countsByGroup.GetWithCheck(groupingKey)
if !present {
tr.countsByGroup.Put(groupingKey, int64(1))
tr.valuesByGroup.Put(groupingKey, selectedValues)
} else {
tr.countsByGroup.Put(groupingKey, iCount.(int64)+1)
}
}
} else { // end of record stream
for pa := tr.countsByGroup.Head; pa != nil; pa = pa.Next {
outrec := mlrval.NewMlrmapAsRecord()
valuesForGroup := tr.valuesByGroup.Get(pa.Key).([]*mlrval.Mlrval)
for i, fieldName := range tr.fieldNames {
outrec.PutCopy(
fieldName,
valuesForGroup[i],
)
}
if tr.showCounts {
outrec.PutReference(
tr.outputFieldName,
mlrval.FromInt(pa.Value.(int64)),
)
}
outputRecordsAndContexts.PushBack(types.NewRecordAndContext(outrec, &inrecAndContext.Context))
}
outputRecordsAndContexts.PushBack(inrecAndContext) // end-of-stream marker
}
}
// ----------------------------------------------------------------
func (tr *TransformerUniq) transformWithoutCounts(
inrecAndContext *types.RecordAndContext,
outputRecordsAndContexts *list.List, // list of *types.RecordAndContext
inputDownstreamDoneChannel <-chan bool,
outputDownstreamDoneChannel chan<- bool,
) {
if !inrecAndContext.EndOfStream {
inrec := inrecAndContext.Record
groupingKey, selectedValues, ok := inrec.GetSelectedValuesAndJoined(tr.fieldNames)
if !ok {
return
}
iCount, present := tr.countsByGroup.GetWithCheck(groupingKey)
if !present {
tr.countsByGroup.Put(groupingKey, int64(1))
tr.valuesByGroup.Put(groupingKey, selectedValues)
outrec := mlrval.NewMlrmapAsRecord()
for i, fieldName := range tr.fieldNames {
outrec.PutCopy(
fieldName,
selectedValues[i],
)
}
outputRecordsAndContexts.PushBack(types.NewRecordAndContext(outrec, &inrecAndContext.Context))
} else {
tr.countsByGroup.Put(groupingKey, iCount.(int64)+1)
}
} else { // end of record stream
outputRecordsAndContexts.PushBack(inrecAndContext) // end-of-stream marker
}
}