1

サイズが約 50GB のアーカイブ ファイルがあります。

毎週、CSV ファイルを取得して、非常に大きな 50 GB の CSV ファイルとマージする必要があります。

私は Go が初めてで、Go での優れた elagent ソリューションを期待していました。

ファイルは次のようになります。

"a:123", 101010
"b:123", 101010
"some-key-here:123", 101010
"some-key-here:234", 101010
4

2 に答える 2

0

チェックのために自分でコンパイルしたことはありませんが、compare()関数を実装すると、これはあなたが望むことをするはずです。これは本質的に、Mergesort アルゴリズムの「マージ」ステップです。既に 2 つのファイルが並べ替えられているため、ストリーミング方式で実行できるマージ ステップのみが必要です。

package main

import (
    "encoding/csv"
    "io"
    "log"
    "os"
)

const outFile = "your/output/file/path.ext"

func main() {
    // make sure there are only 2 args
    if len(os.Args) != 3 {
        log.Panic("\nUsage: command file1 file2")
    }

    // open the first file
    f1, e := os.Open(os.Args[1])
    if e != nil {
        log.Panic("\nUnable to open first file: ", e)
    }
    defer f1.Close()

    // open second file
    f2, e := os.Open(os.Args[2])
    if e != nil {
        log.Panic("\nUnable to open second file: ", e)
    }
    defer f2.Close()

    // create a file writer
    w, e := os.Create(outFile)
    if e != nil {
        log.Panic("\nUnable to create new file: ", e)
    }
    defer w.Close()

    // wrap the file readers with CSV readers
    cr1 := csv.NewReader(f1)
    cr2 := csv.NewReader(f2)

    // wrap the out file writer with a CSV writer
    cw := csv.NewWriter(w)

    // initialize the lines
    line1, b := readline(cr1)
    if !b {
        log.Panic("\nNo CSV lines in file 1.")
    }
    line2, b := readline(cr2)
    if !b {
        log.Panic("\nNo CSV lines in file 2.")
    }

    // copy the files according to similar rules of the merge step in Mergesort
    for {
        if compare(line1, line2) {
            writeline(line1)
            if line1, b = readline(cr1); !b {
                copy(cr2, w)
                break
            }
        } else {
            writeline(line2)
            if line2, b = readline(cr2); !b {
                copy(cr1, w)
                break
            }
        }
    }

    // note the files will be closed here, since we defered it above
}

func readline(r csv.Reader) ([]string, bool) {
    line, e := r.Read()
    if e != nil {
        if e == io.EOF {
            return nil, false
        }
        log.Panic("\nError reading file: ", e)
    }
    return line, true
}

func writeline(w csv.Writer, line []string) {
    e := w.Write(line)
    if e != nil {
        log.Panic("\nError writing file: ", e)
    }
}

func copy(r csv.Reader, w csv.Writer) {
    for line, b := readline(r); !b; r, b = readline(r) {
        writeline(w, line)
    }
}

func compare(line1, line2 string) bool {
    /* here, determine if line1 and line2 are in the correct order (line1 first)
       if so, return true, otherwise false
    */
}

注:この回答は大幅に編集され、リンクの代わりにインラインのコードが含まれています。さらに、コードは私の最初のドラフトから劇的に改善されましたが、ここでは活動がなかったので、古いバージョンを吹き飛ばして回答を書き直しています。

于 2013-03-28T03:44:19.813 に答える