Elasticsearch初探


原文: Elasticsearch初探
date: 2018-01-01 12:39:04


[TOC]

前言

最近這個(gè)好火, 簡(jiǎn)單體驗(yàn)下

一: 安裝和啟動(dòng)

ElasticSearch下載

官方地址: https://www.elastic.co/cn/downloads/elasticsearch

github: https://github.com/elastic/elasticsearch

下載或clone后解壓

單實(shí)例節(jié)點(diǎn)啟動(dòng)

# cd elasticsearch目錄下
bin/elasticsearch
bin/elasticsearch -d # 后臺(tái)啟動(dòng)

默認(rèn)端口9200, 啟動(dòng)完成后訪問http://ip:9200 即可查看到節(jié)點(diǎn)信息

啟動(dòng)中我遇到兩個(gè)錯(cuò)誤:

錯(cuò)誤一:

can not run elasticsearch as root  
# 不能以root用戶啟動(dòng)
[root@01 bin]# groupadd xiefy
[root@01 bin]# useradd xiefy -g xiefy -p 123123
[root@01 bin]# chown -R xiefy:xiefy elasticsearch

錯(cuò)誤二:

ERROR: [2] bootstrap checks failed
[1]: max file descriptors [65535] for elasticsearch process is too low, increase to at least [65536]
[2]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

-- 錯(cuò)誤[1]: max file descriptors過小
-- 錯(cuò)誤[2]: max_map_count過小, max_map_count文件包含限制一個(gè)進(jìn)程可以擁有的VMA(虛擬內(nèi)存區(qū)域)的數(shù)量积锅,系           統(tǒng)默認(rèn)是65530铁瞒,修改成262144
# 切換到root用戶
vi /etc/security/limits.conf

# 添加如下
* soft nofile 65536
* hard nofile 65536
# 切換到root用戶
vi /etc/sysctl.conf

# 添加如下
vm.max_map_count=655360
# 重新加載配置文件或重啟
sysctl -p # 從配置文件“/etc/sysctl.conf”加載內(nèi)核參數(shù)設(shè)置

elasticsearch-head插件安裝

elasticsearch-head 是一個(gè)用于瀏覽Elastic Search集群并與之進(jìn)行交互(操作和管理)的web界面

GitHub: https://github.com/mobz/elasticsearch-head

要使用elasticsearch-head, 需要具備nodejs環(huán)境:

nodejs安裝

下載源碼: https://nodejs.org/en/download/

安裝方式有多種, 我用源碼安裝方式(包含npm)

  1. 下載源碼:

    https://nodejs.org/dist/v8.9.4/node-v8.9.4.tar.gz
    
  2. 解壓源碼:

    tar xzvf node-v* && cd node-v*
    
  3. 安裝必要的編譯軟件

    sudo yum install gcc gcc-c++
    
  4. 編譯

    ./configure
    make
    
  5. 編譯&安裝

    sudo make install
    
  6. 查看版本

    node --version
    npm -version
    

下載或克隆elasticsearch-head后, 進(jìn)入elasticsearch-head-master目錄:

  • npm install

    速度太慢可以使用淘寶鏡像: npm install -g cnpm --registry=https://registry.npm.taobao.org

  • npm run start

  • open http://localhost:9100/

這時(shí)可以訪問到頁(yè)面, 并沒有監(jiān)聽到集群.

解決head插件和elasticsearch之間訪問跨域問題.

修改elasticsearch目錄下的elasticsearch.yml

# 加入以下內(nèi)容
http.cors.enabled: true
http.cors.allow-origin: "*"

然后: http://localhost:9100/ 即可訪問到管理頁(yè)面.

分布式安裝啟動(dòng)

elasticsearch的橫向擴(kuò)展很容易: 這里建立一個(gè)主節(jié)點(diǎn)(node-master), 兩個(gè)隨從節(jié)點(diǎn)(node-1, node-2)

我提前拷貝了三個(gè)es:

[xiefy@01 elk]$ ll
total 33620
-rw-r--r-- 1 root  root  33485703 Aug 17 22:42 elasticsearch-5.5.2.tar.gz
drwxr-xr-x 7 root  root      4096 Jan  8 11:17 elasticsearch-head-master
drwxr-xr-x 9 xiefy xiefy     4096 Jan  8 10:15 elasticsearch-master
drwxr-xr-x 9 xiefy xiefy     4096 Jan  8 14:13 elasticsearch-node1
drwxr-xr-x 9 xiefy xiefy     4096 Jan  8 14:16 elasticsearch-node2
-rw-r--r-- 1 root  root    921421 Jan  8 11:14 master.zip

分別配置三個(gè)es目錄中的config/elasticsearch.yml

node-master:

cluster.name: xiefy_elastic 
node.name: node-master 
node.master: true 
network.host: 0.0.0.0 

# 除此之外, head插件需要連接到port: 9200的節(jié)點(diǎn)上, 還需要這個(gè)配置, 
# 用來允許 elasticsearch-head 運(yùn)行時(shí)的跨域
http.cors.enabled: true
http.cors.allow-origin: "*"

node-1:

cluster.name: xiefy_elastic 
node.name: node-1
network.host: 0.0.0.0
http.port: 9201 
discovery.zen.ping.unicast.hosts: ["127.0.0.1"]

node-2: 參考node-1

相關(guān)配置解釋:

  • cluster.name: 集群名稱, 默認(rèn)是elasticsearch

  • node.name: 節(jié)點(diǎn)名稱, 默認(rèn)隨機(jī)分配

  • node.master: 是否是主節(jié)點(diǎn), 默認(rèn)情況下可不寫, 第一個(gè)起來的就是Master, 掛掉后會(huì)重新選舉Master

  • network.host: 默認(rèn)情況下只允許本機(jī)通過localhost或127.0.0.1訪問, 為了測(cè)試方便,

    我需要遠(yuǎn)程訪問所以配成了0.0.0.0

  • http.port: 默認(rèn)為9200, 同一個(gè)服務(wù)器下啟動(dòng)多個(gè)es節(jié)點(diǎn), 默認(rèn)端口號(hào)會(huì)從9200默認(rèn)遞增1, 這里我手動(dòng)指定了

  • discovery.zen.ping.unicast.hosts: ["host1", "host2"]

    Elasticsearch默認(rèn)使用服務(wù)發(fā)現(xiàn)(Zen discovery)作為集群節(jié)點(diǎn)間發(fā)現(xiàn)和通信的機(jī)制, 當(dāng)啟動(dòng)新節(jié)點(diǎn)時(shí)洛心,通過這個(gè)ip列表進(jìn)行節(jié)點(diǎn)發(fā)現(xiàn)屑那,組建集群.

分別啟動(dòng)三個(gè)es實(shí)例和head插件:

訪問http://ip:9100:

es三個(gè)節(jié)點(diǎn)集群

二: 基礎(chǔ)概念

ElasticSearch與關(guān)系型數(shù)據(jù)庫(kù)的一些術(shù)語(yǔ)比較

關(guān)系型數(shù)據(jù)庫(kù) Ela
Database Index
Table Type
Row Document
Column Field
Schema Mapping
Index Everything is indexed
SQL` Query DSL
select * from table... GET http://...
update tables set... PUT http://...

Server:

  • Node: 一個(gè)server實(shí)例
  • Cluster:多個(gè)node組成cluster
  • Shard:數(shù)據(jù)分片霞扬,一個(gè)index可能會(huì)有多個(gè)shards硼婿,不同shards可能在不同nodes
  • Replica:shard的備份骤肛,有一個(gè)primary shard,其余的叫做replica shards
  • Gateway:管理cluster狀態(tài)信息

Shards & Replicas

副本很重要, 主要有兩個(gè)原因:

  • 它在分片/節(jié)點(diǎn)發(fā)生故障時(shí)來保障高可用性, 因此, 副本分片永遠(yuǎn)不會(huì)和主/原始分片分配在同一個(gè)節(jié)點(diǎn)中
  • 它允許擴(kuò)展搜索量和吞吐量, 因?yàn)榭梢栽谒懈北旧喜⑿袌?zhí)行搜索

可以在創(chuàng)建索引時(shí)為索引定義分片和副本的數(shù)量苔可。
創(chuàng)建索引后,可以隨時(shí)動(dòng)態(tài)更改副本數(shù)袋狞,但不能再更改分片數(shù)焚辅。

每個(gè)Elasticsearch分片都是Lucene索引, 在一個(gè)Lucene上的最大文檔數(shù)量大約21億(Integer.MAX_VALUE-128 )

THE REST API:

elasticsearh提供了豐富的REST API來與集群交互, 這些API包括:

  • 檢查你的集群,節(jié)點(diǎn)和索引的健康情況苟鸯,狀態(tài)和統(tǒng)計(jì)
  • 管理你的集群同蜻,節(jié)點(diǎn),索引數(shù)據(jù)和metadata
  • 針對(duì)索引執(zhí)行CURD(創(chuàng)建早处,讀取湾蔓,更新,刪除)和搜索操作
  • 執(zhí)行高級(jí)的搜索操作砌梆,例如分頁(yè)卵蛉,排序,過濾么库,聚合傻丝,腳本等等。

通過_cat可以查看到很多資源:

curl -XGET 'localhost:9200/_cat'

=^.^=
/_cat/allocation
/_cat/shards
/_cat/shards/{index}
/_cat/master
/_cat/nodes
/_cat/tasks
/_cat/indices
/_cat/indices/{index}
/_cat/segments
/_cat/segments/{index}
/_cat/count
/_cat/count/{index}
/_cat/recovery
/_cat/recovery/{index}
/_cat/health
/_cat/pending_tasks
/_cat/aliases
/_cat/aliases/{alias}
/_cat/thread_pool
/_cat/thread_pool/{thread_pools}
/_cat/plugins
/_cat/fielddata
/_cat/fielddata/{fields}
/_cat/nodeattrs
/_cat/repositories
/_cat/snapshots/{repository}
/_cat/templates

偷偷看一眼集群健康狀態(tài): curl -XGET 'localhost:9200/_cat/health?v'

節(jié)點(diǎn)的信息: curl -XGET 'localhost:9200/_cat/nodes?v&pretty'

而關(guān)于和集群索引和文檔的交互, 放在下一章.

三: 基礎(chǔ)用法

索引創(chuàng)建

  • 方式一: head插件可以直接新建/刪除/查詢索引(Index)

  • 方式二: 通過rest api

    # 新建
    curl -X PUT 'localhost:9200/book'
    
    # 刪除
    curl -X DELETE 'localhost:9200/book'
    
    # 查看當(dāng)前節(jié)點(diǎn)下所有Index
    curl -X GET 'http://localhost:9200/_cat/indices?v'
    

這樣創(chuàng)建的Index是沒有結(jié)構(gòu)的. 可以看到索引信息的mappings:{}

下面來定義一個(gè)有結(jié)構(gòu)映射的Index

PUT http://ip:9200/people

{
    "settings": {
        "number_of_shards": 3,
        "number_of_replicas": 1
    },
    "mappings": {
        "man": {
            "properties": {
                "name": {"type": "text"},
                "country": {"type": "keyword"},
                "age": {"type": "integer"},
                "birthday": {
                    "type": "date",
                    "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
                }
            }
        },
        "women": {
        }
    }
}

里面設(shè)置了分片數(shù), 備份數(shù), 一個(gè)Index和兩個(gè)type的結(jié)構(gòu)映射.

插入數(shù)據(jù)

PUT http://47.94.210.157:9200/people/man/1

指定ID為1

{
    "name": "伊布",
    "country": "瑞典",
    "age": 30,
    "birthday": "1988-12-12"
}

如果不指定ID, 會(huì)生成為隨機(jī)字符串, 此時(shí)需要改為POST方式 POST http://47.94.210.157:9200/people/man

神奇的一點(diǎn), es不會(huì)限制你在創(chuàng)建一個(gè)文檔之前索引和類型必須存在, 不存在時(shí), es會(huì)自動(dòng)創(chuàng)建它.

更新數(shù)據(jù)

POST http://47.94.210.157:9200/people/man/1/_update -- 修改ID為1的文檔

{
    "doc": {
        "name": "梅西梅西很像很強(qiáng)"
    }
}

還可以通過腳本方式更新:

{ "script": "ctx._source.age += 10" }

這里是把年齡加10, ctx.source引用了當(dāng)前文檔.

索引/替換文檔

PUT http://47.94.210.157:9200/football/man/1 -- 修改ID為1的文檔

{"name": "伊布asdasadasds3333333333333333sd"}

elasticsearch將會(huì)用一個(gè)新的文檔取代(即重建索引)舊的文檔

刪除數(shù)據(jù)

刪除文檔: DELETE http://47.94.210.157:9200/people/man/1

查看數(shù)據(jù)

  • 根據(jù)ID查詢

GET http://ip:9200/people/man/1?pretty=true

{
  "_index": "people",
  "_type": "man",
  "_id": "2",
  "_version": 1,
  "found": true,
  "_source": {
    "name": "伊布",
    "country": "瑞典",
    "age": 34,
    "birthday": "1972-12-12"
  }
}

found字段表示查到與否

?

  • 查詢?nèi)?/li>

GET http://ip:9200/Index/Type/_search

或帶排序帶分頁(yè)的查詢:

POST http://47.94.210.157:9200/people/_search

ES 默認(rèn) 從0開始(from), 一次返回10條(size), 并按照_score字段倒排, 也可以自己指定

# 帶排序帶分頁(yè)的查詢
{
    "query": { "match_all": {} },
    "sort": [{
        "birthday": {"order": "desc"}
        }
    ],
    "from": 0, 
    "size": 5
}
{
  "took": 5,
  "timed_out": false,
  "_shards": {
    "total": 3,
    "successful": 3,
    "failed": 0
  },
  "hits": {
    "total": 3,
    "max_score": 1,
    "hits": [
      {
        "_index": "people",
        "_type": "man",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "伊布",
          "country": "瑞典",
          "age": 34,
          "birthday": "1972-12-12"
        }
      },
      ....
      ....
    ]
  }
}
# 返回結(jié)果解釋
- took: 耗時(shí)(單位毫秒)
- timed_out: 是否超時(shí)
- hits: 命中的記錄數(shù)組 
  - total: 返回的記錄數(shù)
  - max_score: 最高匹配度分?jǐn)?shù)
  - hits: 記錄數(shù)組
    - _score: 匹配度
  • 關(guān)鍵字查詢
{
    "query": {
        "match": {"name": "梅西"}
    }
}

注意: 這里是模糊匹配查詢, 例如查詢的值是"西2", 那么會(huì)查詢所有記錄name有"西"和name有"2"的.

關(guān)于查詢多個(gè)關(guān)鍵字之間的邏輯運(yùn)算:

如果這樣寫, 兩個(gè)關(guān)鍵字會(huì)被認(rèn)為是 or的關(guān)系來查詢

{
    "query": {
        "match": {"name": "西 布"}
    }
}

如果是and關(guān)系來搜索, 需要布爾查詢

{
    "query": {
        "bool": {
            "must": [
                {"match": {"name": "西"}} ,
                {"match": {"name": "2"}} 
            ]
        }
    }
}

聚合查詢

POST http://47.94.210.157:9200/people/_search

  • 分組聚合
{
    "aggs": {
        "group_by_age": {
            "terms": {"field": "age"}
        }
    }
}

返回結(jié)果中, 除了有hits數(shù)組, 還有聚合查詢的結(jié)果:

在單個(gè)請(qǐng)求中就可以同時(shí)查詢數(shù)據(jù)和進(jìn)行多次聚合運(yùn)算是非常有意義的, 他可以降低網(wǎng)絡(luò)請(qǐng)求的次數(shù)

# 聚合查詢結(jié)果
"aggregations": {
    "group_by_age": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 24,
          "doc_count": 2
        },
        {
          "key": 32,
          "doc_count": 1
        }
      ]
    }
}

支持多個(gè)聚合, 聚合結(jié)果也會(huì)返回多個(gè):

{
    "aggs": {
        "group_by_age": {
            "terms": {"field": "age"}
        },
        "group_by_age": {
            "terms": {"field": "age"}
        }
    }
}
  • 其他功能函數(shù)
{
    "aggs": {
        "tongji_age": {
            "stats": {"field": "age"}
        }
    }
}

stats指定計(jì)算字段, 返回結(jié)果包括了總數(shù), 最小值, 最大值, 平均值和求和

 "aggregations": {
    "tongji_age": {
      "count": 3,
      "min": 24,
      "max": 32,
      "avg": 26.666666666666668,
      "sum": 80
    }
  }

也可指定某種類型的計(jì)算

{
    "aggs": {
        "tongji_age": {
            "sum": {"field": "age"}
        }
    }
}

返回結(jié)果

"aggregations": {
    "tongji_age": {
      "value": 80
    }
 }

四: 高級(jí)查詢

分為子條件查詢復(fù)合條件查詢:

類型:

  • 全文本查詢: 針對(duì)文本類型數(shù)據(jù)
  • 字段級(jí)別查詢: 針對(duì)結(jié)構(gòu)化數(shù)據(jù), 如日期, 數(shù)字

文本查詢

  • 模糊匹配
{
    "query": {
        "match": {"name": "西2"}
    }
}
  • 短語(yǔ)匹配
{
    "query": {
        "match_phrase": {"name": "西2"}
    }
}
  • 多個(gè)字段匹配
{
    "query": {
        "multi_match": {
            "query": "瑞典",
            "fields": ["name", "country"]
        }
    }
}

語(yǔ)法查詢: 根據(jù)語(yǔ)法規(guī)則查詢:

  • 帶有布爾邏輯的查詢
{
    "query": {
        "query_string": {
            "query": "(西 AND 梅) OR 布"
        }
    }
}
  • query_string 查詢多個(gè)字段
{
    "query": {
        "query_string": {
            "query": "西梅 OR  瑞典",
            "fields": ["country", "name"]
        }
    }
}

結(jié)構(gòu)化數(shù)據(jù)查詢

{
    "query": {"term": { "age": 24}}
}   
  • 帶范圍的查詢
{
    "query": {
        "range": {
            "birthday": {
                "gte": "1980-01-01",
                "lte": "now"
            }
        }
    }
}   

子條件查詢

Filter Context: 用來做數(shù)據(jù)過濾, 在查詢過程中, 只判斷該文檔是否滿足條件(y or not)

Filter和Query的區(qū)別?

Filter要結(jié)合bool使用, 查詢結(jié)果會(huì)放入緩存中, 速度較Query更快

{
    "query": {
        "bool": {
            "filter": {
                "term": { "age": 24 }
            }
        }
    }
}

復(fù)合查詢

  • 固定分?jǐn)?shù)查詢
{
    "query": {
        "match": {"name": "梅西"}
    }
}

可以看到查詢的結(jié)果, 每條數(shù)據(jù)的_score不同, 代表了與查詢值的匹配程度的分?jǐn)?shù).

但查詢不一定都需要產(chǎn)生文檔得分诉儒,特別在過濾文檔集合的時(shí)候葡缰。為了避免不必要的文檔得分計(jì)算,Elasticsearch會(huì)檢查這種情況并自動(dòng)的優(yōu)化這種查詢忱反。

例如在bool查詢中返回年齡范圍在20-50的文檔, 對(duì)我來說這個(gè)范圍內(nèi)的文檔都是等價(jià)的, 即他們的相關(guān)度都是一樣的(filter子句查詢泛释,不會(huì)改變得分).

{
    "query": {
        "constant_score": {
            "filter": {
                "match": {"name": "梅西"}
            },
            "boost": 2
        }
    }
}

可以看到查詢結(jié)果, 每條數(shù)據(jù)的_score都為2, 如果不指定boost則默認(rèn)為1

  • 布爾查詢
{
    "query": {
        "bool": {
            "should": [
                { "match": {"name": "梅西"}},
                { "match": {"country": "阿"}}
            ]
        }
    }   
}

這里兩個(gè)match之間是或的邏輯關(guān)系. should 如果改為 must 代表與邏輯.

我們也可以把mustshould温算,must_not同時(shí)組合到bool子句怜校。此外,我們也可以組合bool 到任何一個(gè)bool子句中注竿,實(shí)現(xiàn)復(fù)雜的多層bool子句嵌套邏輯茄茁。

再加一層Filter, 只有age=32的能返回

{
    "query": {
        "bool": {
            "must": [
                { "match": {"name": "梅西"} },
                { "match": {"country": "阿根廷"}}
            ],
            "filter": [{
                "term": {
                    "age": 32
                }
            }]
        }
    }   
}

country=阿根廷的不返回:

{
    "query": {
        "bool": {
            "must_not": {
                "term": {"country": "阿根廷"}
            }
        }
    }
}

五: 關(guān)于中文分詞

為什么需要中文分詞?

首先看一下默認(rèn)的分詞規(guī)則.

# 英文
GET http://47.94.210.157:9200/_analyze?analyzer=standard&pretty=true&text=hello world, elasticsearch

{
  "tokens": [
    {
      "token": "hello",
      "start_offset": 0,
      "end_offset": 5,
      "type": "<ALPHANUM>",
      "position": 0
    },
    {
      "token": "world",
      "start_offset": 6,
      "end_offset": 11,
      "type": "<ALPHANUM>",
      "position": 1
    },
    {
      "token": "elasticsearch",
      "start_offset": 13,
      "end_offset": 26,
      "type": "<ALPHANUM>",
      "position": 2
    }
  ]
}

可以看到, 英文的默認(rèn)分詞是根據(jù)標(biāo)點(diǎn)符號(hào)和空格默認(rèn)來分的.

再看看中文的:

GET http://47.94.210.157:9200/_analyze?analyzer=standard&pretty=true&text=你好,啊

{
  "tokens": [
    {
      "token": "你",
      "start_offset": 0,
      "end_offset": 1,
      "type": "<IDEOGRAPHIC>",
      "position": 0
    },
    {
      "token": "好",
      "start_offset": 1,
      "end_offset": 2,
      "type": "<IDEOGRAPHIC>",
      "position": 1
    },
    {
      "token": "啊",
      "start_offset": 3,
      "end_offset": 4,
      "type": "<IDEOGRAPHIC>",
      "position": 2
    }
  ]
}

可以看到ES對(duì)中文的分詞并不智能, 是將漢字全部分開了, 所以引入中文分詞.

IK

IK: https://github.com/medcl/elasticsearch-analysis-ik

The IK Analysis plugin integrates Lucene IK analyzer into elasticsearch, support customized dictionary.

安裝

1.download or compile

  • optional 1 - download pre-build package from here: https://github.com/medcl/elasticsearch-analysis-ik/releases

    unzip plugin to folder your-es-root/plugins/

  • optional 2 - use elasticsearch-plugin to install ( version > v5.5.1 ):

    ./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.2.1/elasticsearch-analysis-ik-6.2.1.zip

2.restart elasticsearch

兩種安裝方式, 任選其一, 注意版本就好

Github里有Quick Example 可以看下怎么使用

需要在建立索引時(shí)指定ik分詞器, 建立索引和搜索索引字段都需要指定, 例如:

"analyzer": "ik_max_word""search_analyzer": "ik_max_word"

IK提供兩種分詞規(guī)則:

  • ik_max_word: 會(huì)將文本做最細(xì)粒度的拆分,比如會(huì)將“中華人民共和國(guó)國(guó)歌”拆分為“中華人民共和國(guó),中華人民,中華,華人,人民共和國(guó),人民,人,民,共和國(guó),共和,和,國(guó)國(guó),國(guó)歌”巩割,會(huì)窮盡各種可能的組合裙顽;
  • ik_smart: 會(huì)做最粗粒度的拆分,比如會(huì)將“中華人民共和國(guó)國(guó)歌”拆分為“中華人民共和國(guó),國(guó)歌”宣谈。

除此之外, IK也支持?jǐn)U展自定義詞典, 以及熱更新.

# Test
GET http://47.94.210.157:9200/_analyze?analyzer=ik_max_word&pretty=true&text=你好,啊

{
  "tokens": [
    {
      "token": "你好",
      "start_offset": 0,
      "end_offset": 2,
      "type": "CN_WORD",
      "position": 0
    },
    {
      "token": "啊",
      "start_offset": 3,
      "end_offset": 4,
      "type": "CN_CHAR",
      "position": 1
    }
  ]
}

六: Spring Boot 集成 Elastic Search

版本參考

Spring Boot Version (x) Spring Data Elasticsearch Version (y) Elasticsearch Version (z)
x <= 1.3.5 y <= 1.3.4 z <= 1.7.2*
x >= 1.4.x 2.0.0 <=y < 5.0.0** 2.0.0 <= z < 5.0.0**
服務(wù)器集群ES版本 5.5.2
Spring boot 1.5.9.RELEASE
Elastic Search 5.5.2
log4j-core 2.7

集成步驟

  1. 引入Maven依賴:

    <properties>
     <log4j-core.version>2.7</log4j-core.version>
     <elasticsearch-version>5.5.2</elasticsearch-version>
    </properties>
    
    <dependency>
     <groupId>org.elasticsearch.client</groupId>
     <artifactId>transport</artifactId>
     <version>${elasticsearch.version}</version>
    </dependency>
    
    <!--
    <dependency>
     <groupId>org.elasticsearch</groupId>
     <artifactId>elasticsearch</artifactId>
     <version>${elasticsearch-version}</version>
    </dependency>
    -->
    

    注意: transport中依賴了elasticsearch, 但默認(rèn)是2.4.6版本, 需要指定下elasticsearch的版本5.5.2

  1. 也可以直接引入:

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    

    但是spring-boot-starter-data-elasticsearch只支持到2.4.x版本的es.

    如果使用5.x.x版本ES, 就用上面那種方式單獨(dú)引入ES依賴.

?

  1. 添加配置類

    @Configuration
    public class ElasticSearchConfig {
    
        /** 集群host */
        @Value("${spring.data.elasticsearch.cluster-nodes}")
        private String clusterNodes;
    
        /** 集群名稱 */
        @Value("${spring.data.elasticsearch.cluster-name}")
        private String clusterName;
    
        @Bean
        public TransportClient client() throws UnknownHostException{
    
            InetSocketTransportAddress node = new InetSocketTransportAddress(
                    InetAddress.getByName(clusterNodes), 9300
            );
    
            Settings settings = Settings.builder().put("cluster.name", clusterName).build();
    
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(node);
            return client;
        }
    }
    

    application.properties中配置:

    • spring.data.elasticsearch.cluster-nodes=xxx
    • spring.data.elasticsearch.cluster-name=xxx

測(cè)試用例

簡(jiǎn)單的CRUL操作:

github: https://github.com/thank037/elasticsearch_demo.git

@Link com.thank.elasticsearch.TestElasticSearchCRUD.java

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末愈犹,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子闻丑,更是在濱河造成了極大的恐慌漩怎,老刑警劉巖勋颖,帶你破解...
    沈念sama閱讀 218,525評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異勋锤,居然都是意外死亡饭玲,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門怪得,熙熙樓的掌柜王于貴愁眉苦臉地迎上來咱枉,“玉大人,你說我怎么就攤上這事徒恋〔隙希” “怎么了?”我有些...
    開封第一講書人閱讀 164,862評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵入挣,是天一觀的道長(zhǎng)亿乳。 經(jīng)常有香客問我,道長(zhǎng)径筏,這世上最難降的妖魔是什么葛假? 我笑而不...
    開封第一講書人閱讀 58,728評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮滋恬,結(jié)果婚禮上聊训,老公的妹妹穿的比我還像新娘。我一直安慰自己恢氯,他們只是感情好带斑,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,743評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著勋拟,像睡著了一般勋磕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上敢靡,一...
    開封第一講書人閱讀 51,590評(píng)論 1 305
  • 那天挂滓,我揣著相機(jī)與錄音,去河邊找鬼啸胧。 笑死赶站,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的吓揪。 我是一名探鬼主播亲怠,決...
    沈念sama閱讀 40,330評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼柠辞!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起主胧,我...
    開封第一講書人閱讀 39,244評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤叭首,失蹤者是張志新(化名)和其女友劉穎习勤,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體焙格,經(jīng)...
    沈念sama閱讀 45,693評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡图毕,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,885評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了眷唉。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片予颤。...
    茶點(diǎn)故事閱讀 40,001評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖冬阳,靈堂內(nèi)的尸體忽然破棺而出蛤虐,到底是詐尸還是另有隱情,我是刑警寧澤肝陪,帶...
    沈念sama閱讀 35,723評(píng)論 5 346
  • 正文 年R本政府宣布驳庭,位于F島的核電站,受9級(jí)特大地震影響氯窍,放射性物質(zhì)發(fā)生泄漏饲常。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,343評(píng)論 3 330
  • 文/蒙蒙 一狼讨、第九天 我趴在偏房一處隱蔽的房頂上張望贝淤。 院中可真熱鬧,春花似錦政供、人聲如沸播聪。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)犬耻。三九已至,卻和暖如春执泰,著一層夾襖步出監(jiān)牢的瞬間枕磁,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工术吝, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留计济,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,191評(píng)論 3 370
  • 正文 我出身青樓排苍,卻偏偏與公主長(zhǎng)得像沦寂,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子淘衙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,955評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容