通过javascript循环添加文档到ElasticSearch索引不工作
Add documents to ElasticSearch index through javascript loop does not work
我检索了很多行从我的PostgreSQL数据库(存储在result.rows
),我想把它们添加到我的ElasticSearch索引。
只添加一个文档就可以了:
var r = result.rows[0];
esClient.index({
index: 'families',
type: 'families',
id: r.family_accession,
body: {
'family_accession' : r.family_accession,
'count_seq' : r.count_seq,
'count_taxon' : r.count_taxon
}
}, function (error, response) {
console.log(error);
});
但是当我尝试在循环中调用它时,它根本不起作用:
result.rows.forEach(function (r) {
esClient.index({
index: 'families',
type: 'families',
id: r.family_accession,
body: {
'family_accession' : r.family_accession,
'count_seq' : r.count_seq,
'count_taxon' : r.count_taxon
}
}, function (error, response) {
console.log(error);
});
});
由于您在循环中调用异步代码段,因此在调用esClient.index()
函数时存在的上下文在回调执行时不再存在。
你需要把它包在闭包中,以保持执行上下文。
result.rows.forEach(function (r) {
(function( row ) {
esClient.index({
index: 'families',
type: 'families',
id: row.family_accession,
body: {
'family_accession' : row.family_accession,
'count_seq' : row.count_seq,
'count_taxon' : row.count_taxon
}
}, function (error, response) {
console.log(error);
});
})( r );
});
相关文章:
- 名称输入的索引
- 在jQuery中获取表的行索引
- 测试索引值是否等于某个数字的倍数
- 循环遍历数组中的特定索引
- 按照选项卡索引的顺序循环一个jQuery选择
- 在JavaScript中通过索引从对象数组中获取值
- 尝试在PHP中回显输入文本时出现未定义的索引错误
- 在索引.html和应用.js [node.js] 之间共享变量
- 如何为高图中的区域线创建z索引
- 下拉列表在使用z索引放置在前面后停止工作
- 减去两个索引不同但值相同的整数
- 如何通过所选索引(AngularJS)在模态弹出窗口中显示数据
- Javascript:根据对象的嵌套数组中的值,在数组中查找对象的索引
- 使用 ElasticSearch javascript 客户端创建索引,promise 不会返回
- 如何使用Javascript创建Elasticsearch中的索引,其中行名取自数组
- ElasticSearch - 从 Javascript 搜索 3 个索引
- Node.js上特定索引的Elasticsearch快照失败
- Elasticsearch 5.0和索引模板
- 如何索引源代码与ElasticSearch
- 通过javascript循环添加文档到ElasticSearch索引不工作