简体   繁体   English

通过javascript循环将文档添加到ElasticSearch索引不起作用

[英]Add documents to ElasticSearch index through javascript loop does not work

I retrieved a lot of rows from my PostgreSQL database (stored in result.rows ) and I want to add them into my ElasticSearch index. 我从PostgreSQL数据库中检索了很多行(存储在result.rows ),并将它们添加到我的ElasticSearch索引中。

Add only one document works fine: 仅添加一个文档可以正常工作:

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);
});

But when I try to call it into a loop, it does not work at all: 但是,当我尝试将其调用为循环时,它根本不起作用:

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);
  });
});

Since you're calling an asynchronous piece of code within a loop, the context that was present when the esClient.index() function was called is not present anymore by the time your callback executes. 由于您正在循环中调用异步代码,因此在执行回调时,不再存在在调用esClient.index()函数时出现的上下文。

You need to enclose it in a closure to keep the execution context around. 您需要将其封闭在一个封闭中,以保持执行上下文。

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 );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM