最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在我的web服务的NodeJS发送给elasticsearch回调地狱

运维笔记admin16浏览0评论

在我的web服务的NodeJS发送给elasticsearch回调地狱

在我的web服务的NodeJS发送给elasticsearch回调地狱

我有一个消费者的NodeJS将数据发送到Elasticsearch在2K TPS或多或少的速度。我需要存储的要求,因为我接受他们,如果有任何回应,后来,我需要更新与响应的一些数据的请求的信息。问题是,由于HIGHT TPS,我遇到了很多问题,其中响应到达Elasticsearch请求等..之前,这造成对_doc版本冲突。这是该做的UPSERT我的节点代码的一部分。我需要优化的代码一些帮助。非常感谢提前。

 sendToElasticSearch(index, type, id, body, cb) {
    out('starting sendToElasticSearch()');
    var me = this;
    me.client.exists({
        index: index,
        type: type,
        id: id
    }, function(err, exists) {
        if (err) {
            cb(err)
        } else {
            if (exists === true) {
                out('exists. doing update.');
                // update existing document
                me.client.update({
                    index: index,
                    type: type,
                    id: id,
                    body: body

                }, function(err, resp) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, resp);
                    }
                });
            } else {
                out('adding new document');
                // add new document
                me.client.create({
                    index: index,
                    type: type,
                    id: id,
                    body: body
                }, function(err, resp) {
                    if (err) {
                        cb(err);
                    } else {
                        cb(null, resp);
                    }
                });
            }
       }
    });
}
回答如下:
sendToElasticSearch(index, type, id, body, cb) {
    var self = this;

    function onDone (err, exists) {
        if (err) 
            return cb(err); 

        var do = exists ? 'update' : 'create';
        self[do]({index, type, id, body}, cb);  
    }

    self.client.exists({index, type, id}, onDone);
}
发布评论

评论列表(0)

  1. 暂无评论