【问题标题】:How to use Elasticsearch with MongoDB?如何在 MongoDB 中使用 Elasticsearch?
【发布时间】:2014-07-13 20:39:20
【问题描述】:

我浏览了许多关于配置 Elasticsearch for MongoDB 以索引 MongoDB 中的集合的博客和网站,但没有一个是直截了当的。

请给我解释一下安装elasticsearch的分步过程,应该包括:

  • 配置
  • 在浏览器中运行

我将 Node.js 与 express.js 一起使用,因此请提供相应的帮助。

【问题讨论】:

  • 注意:河流已被弃用

标签: mongodb elasticsearch


【解决方案1】:

这个答案应该足以让您在Building a functional search component with MongoDB, Elasticsearch, and AngularJS 上遵循本教程。

如果您希望对来自 API 的数据使用分面搜索,那么 Matthiasn 的 BirdWatch Repo 是您可能想要查看的内容。

以下是您如何设置单节点 Elasticsearch“集群”来索引 MongoDB,以便在全新 EC2 Ubuntu 14.04 实例上的 NodeJS、Express 应用程序中使用。

确保一切都是最新的。

sudo apt-get update

安装 NodeJS。

sudo apt-get install nodejs
sudo apt-get install npm

Install MongoDB - 这些步骤直接来自 MongoDB 文档。 选择您喜欢的任何版本。我坚持使用 v2.4.9,因为它似乎是 MongoDB-River 支持的最新版本,没有问题。

导入 MongoDB 公共 GPG 密钥。

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

更新您的来源列表。

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

获取 10gen 包。

sudo apt-get install mongodb-10gen

如果您不想要最新版本,请选择您的版本。如果您在 Windows 7 或 8 机器上设置环境,请远离 v2.6,直到他们将其作为服务运行时解决了一些错误。

apt-get install mongodb-10gen=2.4.9

防止您的 MongoDB 安装版本在您更新时被提升。

echo "mongodb-10gen hold" | sudo dpkg --set-selections

启动 MongoDB 服务。

sudo service mongodb start

您的数据库文件默认为 /var/lib/mongo,您的日志文件默认为 /var/log/mongo。

通过 mongo shell 创建一个数据库并将一些虚拟数据推入其中。

mongo YOUR_DATABASE_NAME
db.createCollection(YOUR_COLLECTION_NAME)
for (var i = 1; i <= 25; i++) db.YOUR_COLLECTION_NAME.insert( { x : i } )

现在到Convert the standalone MongoDB into a Replica Set

首先关闭进程。

mongo YOUR_DATABASE_NAME
use admin
db.shutdownServer()

现在我们将 MongoDB 作为服务运行,因此当我们重新启动 mongod 进程时,我们不会在命令行参数中传入“--replSet rs0”选项。相反,我们将其放在 mongod.conf 文件中。

vi /etc/mongod.conf

添加这些行,替换您的数据库和日志路径。

replSet=rs0
dbpath=YOUR_PATH_TO_DATA/DB
logpath=YOUR_PATH_TO_LOG/MONGO.LOG

现在再次打开 mongo shell 以初始化副本集。

mongo DATABASE_NAME
config = { "_id" : "rs0", "members" : [ { "_id" : 0, "host" : "127.0.0.1:27017" } ] }
rs.initiate(config)
rs.slaveOk() // allows read operations to run on secondary members.

现在安装 Elasticsearch。我只是关注这个有用的Gist

确保已安装 Java。

sudo apt-get install openjdk-7-jre-headless -y

暂时坚持使用 v1.1.x,直到 Mongo-River 插件错误在 v1.2.1 中得到修复。

wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb
sudo dpkg -i elasticsearch-1.1.1.deb

curl -L http://github.com/elasticsearch/elasticsearch-servicewrapper/tarball/master | tar -xz
sudo mv *servicewrapper*/service /usr/local/share/elasticsearch/bin/
sudo rm -Rf *servicewrapper*
sudo /usr/local/share/elasticsearch/bin/service/elasticsearch install
sudo ln -s `readlink -f /usr/local/share/elasticsearch/bin/service/elasticsearch` /usr/local/bin/rcelasticsearch

如果您现在只在单个节点上开发,请确保 /etc/elasticsearch/elasticsearch.yml 启用了以下配置选项:

cluster.name: "MY_CLUSTER_NAME"
node.local: true

启动 Elasticsearch 服务。

sudo service elasticsearch start

验证它是否正常工作。

curl http://localhost:9200

如果你看到这样的东西,那你很好。

{
  "status" : 200,
  "name" : "Chi Demon",
  "version" : {
    "number" : "1.1.2",
    "build_hash" : "e511f7b28b77c4d99175905fac65bffbf4c80cf7",
    "build_timestamp" : "2014-05-22T12:27:39Z",
    "build_snapshot" : false,
    "lucene_version" : "4.7"
  },
  "tagline" : "You Know, for Search"
}

现在安装 Elasticsearch 插件,以便它可以与 MongoDB 一起使用。

bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb/1.6.0
bin/plugin --install elasticsearch/elasticsearch-mapper-attachments/1.6.0

这两个插件不是必需的,但它们非常适合测试查询和可视化索引更改。

bin/plugin --install mobz/elasticsearch-head
bin/plugin --install lukas-vlcek/bigdesk

重启 Elasticsearch。

sudo service elasticsearch restart

最后从 MongoDB 中索引一个集合。

curl -XPUT localhost:9200/_river/DATABASE_NAME/_meta -d '{
  "type": "mongodb",
  "mongodb": {
    "servers": [
      { "host": "127.0.0.1", "port": 27017 }
    ],
    "db": "DATABASE_NAME",
    "collection": "ACTUAL_COLLECTION_NAME",
    "options": { "secondary_read_preference": true },
    "gridfs": false
  },
  "index": {
    "name": "ARBITRARY INDEX NAME",
    "type": "ARBITRARY TYPE NAME"
  }
}'

检查您的索引是否在 Elasticsearch 中

curl -XGET http://localhost:9200/_aliases

检查您的集群运行状况。

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

它可能是黄色的,带有一些未分配的碎片。我们必须告诉 Elasticsearch 我们想要使用什么。

curl -XPUT 'localhost:9200/_settings' -d '{ "index" : { "number_of_replicas" : 0 } }'

再次检查集群运行状况。它现在应该是绿色的。

curl -XGET 'http://localhost:9200/_cluster/health?pretty=true'

去玩吧。

【讨论】:

  • @Duck5auce 确实知道如何通过 express.js 获取结果(弹性搜索结果)并使用jade或ejs模板在浏览器中显示,例如 app.get('search= "谷歌"',function(req,res){});并感谢您的精彩回答
  • @bibindavid 我会检查这个资源。它会引导您创建一个服务器端 ES 客户端模块,您可以通过其他两个自定义模块推送过滤后的查询。数据的渲染仍然在客户端处理,但它应该是一个不错的起点。 sahan.me/posts/dabbling-in-elasticsearch-part-2-with-nodejs Github repo 位于此处:github.com/sahan/sahan.github.io/tree/master/resources/…
  • 距离duck5auce 的出色回答已经一年了。想想人们现在正在使用 10gens [mongo-connector][1] 将 MongoDB 集群与 ElasticSearch 实时同步。它尾随 MongoDB oplog。 [1]:github.com/10gen-labs/mongo-connector/wiki/…
  • 从 v1.5.0 开始,河流服务已被弃用。虽然您仍然可以使用 River 插件,但不建议这样做,因为它可能在未来的版本中不复存在。
  • @duck5auce 请更新这个答案,它已经过时了。 River has been deprecated
【解决方案2】:

当您的运营规模扩大时,使用河流可能会出现问题。 River 在繁重的操作下会使用大量的内存。我建议您实现自己的 elasticsearch 模型,或者如果您使用的是 mongoose,您可以直接在其中构建您的 elasticsearch 模型,或者使用 mongoosastic,这实际上是为您完成的。

Mongodb River 的另一个缺点是您将无法使用 mongodb 2.4.x 分支和 ElasticSearch 0.90.x。你会开始发现你错过了很多非常好的特性,而且 mongodb River 项目只是没有足够快地生产出可用的产品来保持稳定。也就是说,Mongodb River 绝对不是我投入生产的东西。它带来的问题多于其价值。它会在重负载下随机丢弃写入,它会消耗大量内存,并且没有设置上限。此外,river 不会实时更新,它会从 mongodb 读取 oplog,根据我的经验,这可能会延迟长达 5 分钟的更新。

我们最近不得不重写我们项目的大部分内容,因为每周都会发生 ElasticSearch 出现问题。我们甚至聘请了一名 Dev Ops 顾问,他也同意最好离开 River。

更新: Elasticsearch-mongodb-river 现在支持 ES v1.4.0 和 mongodb v2.6.x。但是,您仍然可能会在繁重的插入/更新操作中遇到性能问题,因为此插件将尝试读取 mongodb 的 oplog 以进行同步。如果自锁(或闩锁)解锁后有很多操作,您会注意到弹性搜索服务器上的内存使用率极高。如果您计划进行大型操作,河流不是一个好的选择。 ElasticSearch 的开发人员仍然建议您通过使用您的语言的客户端库直接与他们的 API 通信来管理自己的索引,而不是使用 River。这不是河流的真正目的。 Twitter-river 是应如何使用河流的一个很好的例子。它本质上是一种从外部来源获取数据的好方法,但对于高流量或内部使用来说不是很可靠。

还要考虑 mongodb-river 版本落后,因为它不是由 ElasticSearch 组织维护,而是由第三方维护。在 v1.0 发布后很长一段时间开发都停留在 v0.90 分支上,当发布 v1.0 的版本时,它并不稳定,直到 elasticsearch 发布 v1.3.0。 Mongodb 版本也落后了。当您希望迁移到每个版本的更高版本时,您可能会发现自己陷入了困境,尤其是 ElasticSearch 处于如此繁重的开发环境中,许多非常值得期待的功能正在开发中。紧跟最新的 ElasticSearch 非常重要,因为我们非常依赖不断改进搜索功能作为我们产品的核心部分。

总而言之,如果您自己动手,您可能会得到更好的产品。它不是那么困难。它只是在您的代码中管理的另一个数据库,它可以轻松地放入您现有的模型中,而无需进行重大重构。

【讨论】:

  • 你有链接或建议,我可以将作者信息编入出版物索引,因为出版物和作者在 2 个集合中,并通过 referenceone 和 referencemany 链接
  • 这将解释您如何加入/关联数据elastic.co/guide/en/elasticsearch/guide/current/…
  • Elasticsearch 是一个文档存储数据库,而不是一个关系数据库。在 elasticsearch 中关联数据并非不可能,但更容易发生非规范化,但可以通过额外的逻辑进行管理(有插件)。关联数据的最常见方式(如上面链接中的状态)是将 ID 引用存储在相关文档中。确保将此 ID 存储在设置为 not_analyzed 的字段中,否则您将无法查询它,请按照分析字段的标记方式进行操作。
【解决方案3】:

这里如何在 mongodb 3.0 上执行此操作。我用了这个不错的blog

  1. 安装 mongodb。
  2. 创建数据目录:
$ mkdir RANDOM_PATH/node1
$ mkdir RANDOM_PATH/node2> 
$ mkdir RANDOM_PATH/node3
  1. 启动 Mongod 实例
$ mongod --replSet test --port 27021 --dbpath node1
$ mongod --replSet test --port 27022 --dbpath node2
$ mongod --replSet test --port 27023 --dbpath node3
  1. 配置副本集:
$ mongo
config = {_id: 'test', members: [ {_id: 0, host: 'localhost:27021'}, {_id: 1, host: 'localhost:27022'}]};    
rs.initiate(config);
  1. 安装 Elasticsearch:
a. Download and unzip the [latest Elasticsearch][2] distribution

b. Run bin/elasticsearch to start the es server.

c. Run curl -XGET http://localhost:9200/ to confirm it is working.
  1. 安装和配置 MongoDB River:

$ bin/plugin --install com.github.richardwilly98.elasticsearch/elasticsearch-river-mongodb

$ bin/plugin --install elasticsearch/elasticsearch-mapper-attachments

  1. 创建“河流”和索引:

curl -XPUT 'http://localhost:8080/_river/mongodb/_meta' -d '{ “类型”:“mongodb”, “蒙哥”:{ “分贝”:“我的分贝”, “收藏”:“富” }, “指数”: { “名称”:“名称”, “类型”:“随机” } }'

  1. 在浏览器上测试:

    http://localhost:9200/_search?q=home

【讨论】:

  • ElasticSearch 已弃用 River 插件。这肯定不是维护搜索索引的最佳方式。
【解决方案4】:

我发现 mongo-connector 很有用。它来自 Mongo Labs (MongoDB Inc.),现在可以与 Elasticsearch 2.x 一起使用

Elastic 2.x 文档管理器:https://github.com/mongodb-labs/elastic2-doc-manager

mongo-connector 创建从 MongoDB 集群到一个或多个目标系统的管道,例如 Solr、Elasticsearch 或另一个 MongoDB 集群。它将 MongoDB 中的数据同步到目标,然后跟踪 MongoDB oplog,实时跟上 MongoDB 中的操作。它已经用 Python 2.6、2.7 和 3.3+ 进行了测试。 wiki 上提供了详细的文档。

https://github.com/mongodb-labs/mongo-connector https://github.com/mongodb-labs/mongo-connector/wiki/Usage%20with%20ElasticSearch

【讨论】:

    【解决方案5】:

    如果您想获得几乎实时的同步和通用解决方案,River 是一个很好的解决方案。

    如果您已经在 MongoDB 中拥有数据,并且希望像“one-shot”一样轻松地将其发送到 Elasticsearch,您可以尝试我在 Node.js https://github.com/itemsapi/elasticbulk 中的包。

    它使用 Node.js 流,因此您可以从支持流的所有内容(即 MongoDB、PostgreSQL、MySQL、JSON 文件等)导入数据

    MongoDB 到 Elasticsearch 的示例:

    安装包:

    npm install elasticbulk
    npm install mongoose
    npm install bluebird
    

    创建脚本,即 script.js:

    const elasticbulk = require('elasticbulk');
    const mongoose = require('mongoose');
    const Promise = require('bluebird');
    mongoose.connect('mongodb://localhost/your_database_name', {
      useMongoClient: true
    });
    
    mongoose.Promise = Promise;
    
    var Page = mongoose.model('Page', new mongoose.Schema({
      title: String,
      categories: Array
    }), 'your_collection_name');
    
    // stream query 
    var stream = Page.find({
    }, {title: 1, _id: 0, categories: 1}).limit(1500000).skip(0).batchSize(500).stream();
    
    elasticbulk.import(stream, {
      index: 'my_index_name',
      type: 'my_type_name',
      host: 'localhost:9200',
    })
    .then(function(res) {
      console.log('Importing finished');
    })
    

    发送您的数据:

    node script.js
    

    它不是非常快,但它可以处理数百万条记录(感谢流)。

    【讨论】:

      【解决方案6】:

      由于 mongo-connector 现在似乎已死,我的公司决定构建一个工具,用于使用 Mongo 更改流输出到 Elasticsearch。

      我们的初步结果看起来很有希望。你可以在https://github.com/electionsexperts/mongo-stream查看。我们仍处于开发初期,欢迎提出建议或贡献。

      【讨论】:

        【解决方案7】:

        在这里,我找到了另一个将 MongoDB 数据迁移到 Elasticsearch 的好选择。 一个将 mongodb 实时同步到 elasticsearch 的 go 守护进程。 它的Monstache。可在:Monstache

        在初始设置下配置和使用它。

        第 1 步:

        C:\Program Files\MongoDB\Server\4.0\bin>mongod --smallfiles --oplogSize 50 --replSet test
        

        第 2 步:

        C:\Program Files\MongoDB\Server\4.0\bin>mongo
        
        C:\Program Files\MongoDB\Server\4.0\bin>mongo
        MongoDB shell version v4.0.2
        connecting to: mongodb://127.0.0.1:27017
        MongoDB server version: 4.0.2
        Server has startup warnings:
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
        2019-01-18T16:56:44.931+0530 I CONTROL  [initandlisten]
        MongoDB Enterprise test:PRIMARY>
        

        第 3 步:验证复制。

        MongoDB Enterprise test:PRIMARY> rs.status();
        {
                "set" : "test",
                "date" : ISODate("2019-01-18T11:39:00.380Z"),
                "myState" : 1,
                "term" : NumberLong(2),
                "syncingTo" : "",
                "syncSourceHost" : "",
                "syncSourceId" : -1,
                "heartbeatIntervalMillis" : NumberLong(2000),
                "optimes" : {
                        "lastCommittedOpTime" : {
                                "ts" : Timestamp(1547811537, 1),
                                "t" : NumberLong(2)
                        },
                        "readConcernMajorityOpTime" : {
                                "ts" : Timestamp(1547811537, 1),
                                "t" : NumberLong(2)
                        },
                        "appliedOpTime" : {
                                "ts" : Timestamp(1547811537, 1),
                                "t" : NumberLong(2)
                        },
                        "durableOpTime" : {
                                "ts" : Timestamp(1547811537, 1),
                                "t" : NumberLong(2)
                        }
                },
                "lastStableCheckpointTimestamp" : Timestamp(1547811517, 1),
                "members" : [
                        {
                                "_id" : 0,
                                "name" : "localhost:27017",
                                "health" : 1,
                                "state" : 1,
                                "stateStr" : "PRIMARY",
                                "uptime" : 736,
                                "optime" : {
                                        "ts" : Timestamp(1547811537, 1),
                                        "t" : NumberLong(2)
                                },
                                "optimeDate" : ISODate("2019-01-18T11:38:57Z"),
                                "syncingTo" : "",
                                "syncSourceHost" : "",
                                "syncSourceId" : -1,
                                "infoMessage" : "",
                                "electionTime" : Timestamp(1547810805, 1),
                                "electionDate" : ISODate("2019-01-18T11:26:45Z"),
                                "configVersion" : 1,
                                "self" : true,
                                "lastHeartbeatMessage" : ""
                        }
                ],
                "ok" : 1,
                "operationTime" : Timestamp(1547811537, 1),
                "$clusterTime" : {
                        "clusterTime" : Timestamp(1547811537, 1),
                        "signature" : {
                                "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
                                "keyId" : NumberLong(0)
                        }
                }
        }
        MongoDB Enterprise test:PRIMARY>
        

        第 4 步。 下载“https://github.com/rwynn/monstache/releases”。 解压缩下载并调整您的 PATH 变量以包含您平台的文件夹路径。 转到 cmd 并输入 "monstache -v" # 4.13.1 Monstache 使用 TOML 格式进行配置。配置名为 config.toml 的迁移文件

        第 5 步。

        我的 config.toml -->

        mongo-url = "mongodb://127.0.0.1:27017/?replicaSet=test"
        elasticsearch-urls = ["http://localhost:9200"]
        
        direct-read-namespaces = [ "admin.users" ]
        
        gzip = true
        stats = true
        index-stats = true
        
        elasticsearch-max-conns = 4
        elasticsearch-max-seconds = 5
        elasticsearch-max-bytes = 8000000 
        
        dropped-collections = false
        dropped-databases = false
        
        resume = true
        resume-write-unsafe = true
        resume-name = "default"
        index-files = false
        file-highlighting = false
        verbose = true
        exit-after-direct-reads = false
        
        index-as-update=true
        index-oplog-time=true
        

        第 6 步。

        D:\15-1-19>monstache -f config.toml
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-02-06
          • 2017-01-13
          • 1970-01-01
          • 2021-12-22
          • 2018-12-31
          • 2017-06-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多