在node.js环境中将mongodb与elasticsearch集成 [英] Integration of mongodb with elasticsearch in node.js environment
问题描述
我正在一个具有以下设置的项目:
I am working on a project which has following setup:
- 我有一个Amazon EC2集群,其中有一个主服务器,3个配置服务器和3个分片服务器.
- Master运行的node.js应用程序基本上是使用Express.js模块编写的REST API.
- 我正在使用mongodb作为数据库.主服务器正在运行"mongos"服务,该服务将数据分片到3个分片服务器中.这些服务器上运行着"mongod"服务.
通过此设置,我想集成elasticsearch来执行搜索查询.为此,我想在我的node.js REST API应用程序中添加一条路由,以对存储在分片中的数据执行搜索查询.
With this setup, I want to integrate elasticsearch to perform search queries. To do this I want to add a route in my node.js REST API application to perform search query on the data stored in shards.
考虑到我有三个在独立计算机上运行的分片,是否还需要执行其他步骤?如何配置Elasticsearch以访问分片中的数据以建立索引?它会自动检测到此配置并建立索引吗?有人可以为我提供完成该步骤应遵循的步骤吗?
Are there any additional steps involved given that I have three shards running on independent machines? How do I configure elasticsearch to access the data from the shards to build index? Does it detect this configuration automatically and builds the index? Can someone please provide me the steps that I should follow to accomplish this?
推荐答案
我已经这样做了:
我正在使用sails.js框架作为节点,并使用mongo作为数据库.
I am using sails.js framework for node and using mongo as DB.
首先,我已经使用npm安装了elasticsearch模块. 然后将此代码添加到配置部分中名为 elasticSeach.js 的文件中.
First of all, i've installed elasticsearch module using npm. Then added this code in a file called elasticSeach.js in config section.
它具有以下代码:
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索引方法索引值的示例,该方法需要:
After that, simply create a file ElasticSearchService.js in which you will do all the operations like search, update etc. Here is an example of an elasticsearch index method to index the values, which takes :
a)类型
b)项目,它是
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);
});
});
}
随时随地调用此方法.
我正在使用诺言返回值. 您无需担心分片实现及其他所有问题. Elastic会解决这个问题.
I am using a promise to return values. You don't need to worry about shard implementation and all. Elastic takes care of that.
此处提供有关类型和映射的更多信息: https://www .elastic.co/guide/en/elasticsearch/guide/current/mapping.html
More about type and mappings here : https://www.elastic.co/guide/en/elasticsearch/guide/current/mapping.html
这篇关于在node.js环境中将mongodb与elasticsearch集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!