0

我正在做一些JSON響應的處理,並希望將結果數據上傳到cloudsearch。最佳文檔從建立的對象上傳到CloudSearch

const AWS = require("aws-sdk"); 
const JSONStream = require("JSONStream"); 
const jsonStream = JSONStream.parse("*"); 
const csd = AWS.CloudSearchDomain(config); 

jsonStream.on("data", processData); 

request.get(resultUrl).pipe(jsonStream); 

function processData(data) { 
    data = doProcessData(data); 

    /* 
    * `data` is now a JSON object ready to be uploaded to CloudSearch 
    * e.g. {type: "add", id: "random-id", fields: {field: "a"}} 
    */ 

    csd.uploadDocuments({contentType: "application/json", documents: [data]}); 
} 

這工作,但AWS suggests

爲了獲得最佳的上載性能,羣組中有接近最大批量添加和刪除操作,我可以在同一時間做這一個文件批量大小

我在考慮將文檔寫入文件並檢查文件大小,並在文件大小爲3MB時上傳文件。我能得到接近5MB,但我不想去了批量大小:

/* Please ignore semantic errors */ 
filename = "/tmp/foo.json"; 
file = fs.createWriteStream(filename); 
file.write("["); 
// in `processData` 
    file.write(JSON.stringify(data)); 

    const stats = file.stat(filename); 
    if (stats.size > 3000000) { 
    file.write("]"); 
    csd.uploadDocuments({documents: fs.createReadStream(filename)}); 
    fs.trunate(filename); 
    } 
    else { 
    file.write(","); 
    } 

這個方法是好的,但是這將是很好有一個更好的辦法來確定文件是否已準備好上傳。如果可以的話,我也寧願避免使用文件系統。

我也可以做這樣的事情做到這一點內存:

const stringifier = JSONStream.stringify("[", ",", "]"); 
    // in `processData` 
    csd.uploadDocuments({documents: stringifier}); 
    stringifier.write(data); 

然而批量大小可能超越5MB。我也不確定如何檢查已寫入JSON流的數據量。

有沒有一種將派生文檔寫入CloudSearch的好方法?如果不這樣做,是否有一種簡單的方法來檢查有多少空間寫入到一個流中,以及一個變量使用多少空間?

回答

0

這只是用於下載大文件,獲取大小和處理大小的概念。讀循環期間的計數將是流的每個字節[1024]塊。

@Override 
protected String doInBackground(String... f_url) { 
    try { 
     int count; 
     File directory = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "/"); 
     if (!directory.exists()) { 
      if (!directory.mkdirs()) { 
       throw new Exception("Could not create directory?!?!?"); 
      } 
     } 
     String filePath = Environment.getExternalStorageDirectory().getAbsoluteFile() + "/ItemLocalStorage.db"; 
     URL url = new URL(f_url[0]); 
     URLConnection urlConnection = url.openConnection(); 
     urlConnection.connect(); 
     int contentLength = urlConnection.getContentLength(); 
     InputStream input = new BufferedInputStream(url.openStream(), 8192); 
     OutputStream output = new FileOutputStream(filePath); 
     byte data[] = new byte[1024]; 
     int byt = 0; 
     int mb = 0; 
     int mbLength; 
     while ((count = input.read(data)) != -1) { 
      if (!isCancelled()) { 
       byt += count; 
       mb = ((byt/1024)/1024 
       mbLength = ((contentLength/1024)/1024); 
       output.write(data, 0, count); 
      } 
     } 
     if (isCancelled()) { 
      output.write(0); 
     } 
     output.flush(); 
     output.close(); 
     input.close(); 
     return filePath; 
    } catch (Exception e) { 
     Log.e("Error: ", e.getMessage()); 
     return null; 
    } 
}