gpt4 book ai didi

node.js - Node.js环境下mongodb与elasticsearch的集成

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:55 25 4
gpt4 key购买 nike

我正在开发一个具有以下设置的项目:

  • 我有一个 Amazon EC2 集群,其中包含 1 个主服务器、3 个配置服务器和 3 个分片服务器。
  • Master 有一个正在运行的 Node.js 应用程序,它基本上是使用 Express.js 模块编写的 REST API。
  • 我使用 mongodb 作为数据库。 Master 运行着“mongos”服务,它将数据分片到 3 个分片服务器中。这些服务器上运行着“mongod”服务。

通过此设置,我想集成 elasticsearch 来执行搜索查询。为此,我想在我的 Node.js REST API 应用程序中添加一条路由,以对存储在分片中的数据执行搜索查询。

鉴于我在独立机器上运行三个分片,是否涉及任何其他步骤?如何配置elasticsearch来访问分片中的数据来构建索引?它会自动检测此配置并构建索引吗?有人可以向我提供实现此目标应遵循的步骤吗?

最佳答案

我是这样做的:

我使用 sails.js 框架作为 Node ,并使用 mongo 作为数据库。

首先,我使用 npm 安装了 elasticsearch 模块。然后将此代码添加到配置部分中名为 elasticSeach.js 的文件中。

它有以下代码:

var elasticsearch = require('elasticsearch'),

index = "Ur_elastic_index_name_goes_here",
client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});

module.exports.elasticSearchClient = client;

module.exports.elasticSearchConfig = {
index: index
};

之后,只需创建一个文件ElasticSearchService.js,您将在其中执行搜索、更新等所有操作。这是一个用于索引值的elasticsearch索引方法的示例,该方法需要:

a) 类型

b) item,这是一个像

这样的json类型的对象
item = {
"name" : "vishal",
"website" : "stackOverflow"
};

方法是

function indexItem(type, item) {
return Q.promise(function(resolve, reject){
elasticSearchClient
.index({
index: elasticSearchConfig.index,
type: type,
body: item
})
.then(function (response) {
sails.log.info("ElasticSearchService#indexItem :: Response :: ", response);
return resolve(response);
})
.catch(function(err) {
sails.log.error("ElasticSearchService#indexItem :: Error :: ", err);
return reject(err);
});
});
}

从任何您想要的地方调用此方法。

我正在使用 promise 返回值。您无需担心分片实现等问题。 Elastic 会处理这个问题。

有关类型和映射的更多信息:https://www.elastic.co/guide/en/elasticsearch/guide/current/mapping.html

关于node.js - Node.js环境下mongodb与elasticsearch的集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38423759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com