搭建ElasticSearch+MongoDB檢索系統


  ElasticSearch是一個基於Lucene的搜索服務器。它提供了一個分布式多用戶能力的全文搜索引擎,基於RESTful web接口。Elasticsearch是用Java開發的,並作為Apache許可條款下的開放源碼發布,是當前流行的企業級搜索引擎。設計用於雲計算中,能夠達到實時搜索,穩定,可靠,快速,安裝使用方便。

       以上是百度百科對ES的介紹。本文主要記述在linux環境下安裝Elasticsearch及基本的可視化工具sense,並使用ES索引MongoDB中的數據,使我們可以直接通過ES去檢索數據庫中的數據,使檢索速度大大加快,並使用python去完成對ES的檢索操作。

環境:ubuntu 14.04, elasticsearch 2.3.4, mongodb 3.2, python 2.7

1.安裝ElasticSearch

    首先官方文檔要求Elasticsearch 至少安裝有Java 7. 因此首先確定已經安裝有JDK7或以上版本。

    安裝ElasticSearch非常簡單,只需要去官方下載地址https://www.elastic.co/downloads/elasticsearch下載想要安裝的版本即可,例如下載2.3.4版本,下載完畢后解壓,接着進入bin目錄下

 cd elasticsearch-2.3.4/bin

    運行

./elasticsearch
接着打開瀏覽器,輸入localhost:9200,如果出現以下信息則啟動成功
{
  "name" : "Tethlam",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "2.3.4",
    "build_hash" : "e455fd0c13dceca8dbbdbb1665d068ae55dabe3f",
    "build_timestamp" : "2016-06-30T11:24:31Z",
    "build_snapshot" : false,
    "lucene_version" : "5.5.0"
  },
  "tagline" : "You Know, for Search"
}

2.安裝kibana和sense

    kibana是ES的可視化工具,功能強大,sense是kibana的一個插件,使用sense可以直接在瀏覽器里完成對ES的基本操作。
    首先安裝kibana,安裝方法與ES一樣,首先下載想要的版本https://www.elastic.co/downloads/kibana,然后解壓,進入bin目錄,運行以下命令安裝sense

 ./bin/kibana plugin --install elastic/sense
安裝成功后運行 ./bin/kibana
打開瀏覽器,輸入http://localhost:5601/app/sense即可進入sense

至此一個基本的ES環境就安裝完成了

3.安裝mongo-connector

    接下來我們要使用ES去檢索mongodb中的數據,這樣首先需要用ES去同步存儲在mongodb中數據,創建這些數據的索引。完成這一步工作需要使用的工具是mongo-connector,這是mongodb官方開發的一個非正式工具。

    使用mongo-connector同步數據首先需要確保mongodb為副本集,這一步是必不可少的,因為ES是通過mongodb的oplog去建立索引,如果不是副本集就沒有oplog,當然也就無法建立索引了,至於如何建立mongodb副本集請自行查閱mongodb文檔。

    可以使用pip直接安裝mongo-connector:

 pip install mongo-connector

然后下載 https://github.com/mongodb-labs/elastic2-doc-manager,接着可以直接運行以下命令完成數據同步
mongo-connector -m localhost:27017 -t localhost:9200 -d elastic2_doc_manager
注意如果使用的ES為1.x版本需要下載 https://github.com/mongodb-labs/elastic-doc-manager並運行
mongo-connector -m localhost:27017 -t localhost:9200 -d elastic_doc_manager

其中-m之后的參數為數據庫地址,-t之后為ES地址,這樣就完成了同步

4.用python操作ES

    最后我們要使用python操作ES,對此ES本身提供了python client,同樣使用pip即可安裝

 pip install elasticsearch

接着可以使用以下代碼測試
from elasticsearch import Elasticsearch
es = Elasticsearch()

# ignore 400 cause by IndexAlreadyExistsException when creating an index
es.indices.create(index='test-index', ignore=400)

# ignore 404 and 400
es.indices.delete(index='test-index', ignore=[400, 404])

更多信息請參考官方文檔

 

相關鏈接:ES官方文檔https://www.elastic.co/guide/index.html

                    mongo-connector文檔https://github.com/mongodb-labs/mongo-connector/wiki/Usage-with-ElasticSearch

                    Elasticsearch python client文檔https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM