我正在对 JSON 响应进行一些处理,并希望将结果数据上传到 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 :
To get the best possible upload performance, group add and delete operations in batches that are close to the maximum batch size
我想我可以将文档写入一个文件,检查文件大小,然后在文件大约 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 的好方法?如果做不到这一点,是否有一种简单的方法来检查已向流写入了多少空间,甚至变量正在使用多少空间?
最佳答案
这只是我用于下载大文件、获取大小以及处理大小的概念。读取循环期间的计数将是流的每个字节[1024] block 。
@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;
}
}
关于javascript - 从构建对象上传到 CloudSearch 的最佳文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35904459/