Sum column in stream using node

↘锁芯ラ 提交于 2021-01-29 07:18:22

问题


My goal is to count the sum of a column which correlates to another column in a csv.

For example, I have an input csv what looks like this

"500","my.jpg"
"500","my.jpg"
"200","another.jpg"

I want the output to be:

[{ bytes: 1000, uri: "my.jpg" }, { bytes:200, "another.jpg" }]

Note: I need to do this as a stream as there can be over 3 millions records for a given csv and looping is just too slow.

I have managed to accomplish this using awk but I am struggling to implement it in node

Here is bash script using awk command

awk -F, 'BEGIN { print "["}
{   
    gsub(/"/, ""); # Remove all quotation from csv
    uri=$2; # Put the current uri in key
    a[uri]++; # Increment the count of uris
    b[uri] = b[uri] + $1; # total up bytes
} 
END { 
    for (i in a) {
        printf "%s{\"uri\":\"%s\",\"count\":\"%s\",\"bytes\":\"%s\"}",
        separator, i, a[i], b[i]
        separator = ", "
    }

    print "]"
}
' ./res.csv

any pointers in the right direction would be hugely appreciated


回答1:


You can try creating a read stream to you csv file and piping it to a csv-streamify parser.

const csv = require('csv-streamify')
const fs = require('fs')

const parser = csv()
const sum = {};

// emits each line as a buffer or as a string representing an array of fields
parser.on('data', function (line) {
  let key = line[1];
  let val = line[0];
  if (!sum[key]) {
    sum[key] = 0;
  }
  sum[key] = sum[key] + parseInt(val);
  console.log("Current sum for " + key + ": " + sum[key])
})

parser.on('end', function () {
  let results = Object.keys(sum)
    .map(key => ({ bytes: sum[key], uri: key }))
  console.log(results);
})

// now pipe some data into it
fs.createReadStream('./test.csv').pipe(parser)

Using your sample data this example should print:

[ { bytes: 1000, uri: 'my.jpg' },
  { bytes: 200, uri: 'another.jpg' } ]



回答2:


You can try the below Perl solution as well.

$ cat url.txt
"500","my.jpg"
"500","my.jpg"
"200","another.jpg"
"600","more.jpg"

$ perl -lne ' if(/\"(\d+)\",\"(.+?)\"/g) { $kv{$2}+=$1} ; END { print "["; for(keys %kv) { print "$s { bytes:$kv{$_} uri:\"$_\" } ";$s="," } print "]" } ' url.txt
[
 { bytes:600 uri:"more.jpg" }
, { bytes:200 uri:"another.jpg" }
, { bytes:1000 uri:"my.jpg" }
]

$


来源:https://stackoverflow.com/questions/54226464/sum-column-in-stream-using-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!