下表是Elasticsearch與MySQL數(shù)據(jù)庫邏輯結(jié)構(gòu)概念的對比
Elasticsearch 關(guān)系型數(shù)據(jù)庫Mysql
索引(index) 數(shù)據(jù)庫(databases)
類型(type) 表(table)
文檔(document) 行(row)
下載ElasticSearch 5.6.8版本
https://www.elastic.co/downloads/past-releases/elasticsearch-5-6-8
無需安裝,解壓安裝包后即可使用
在命令提示符下,進(jìn)入ElasticSearch安裝目錄下的bin目錄,執(zhí)行命令,即可啟用
elasticsearch
9200,9300端口啟動(dòng)后,打開瀏覽器,在地址欄輸入http://127.0.0.1:9200/ 即可看到輸出結(jié)果
{
"name" : "uV2glMR",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "RdV7UTQZT1‐Jnka9dDPsFg",
"version" : {
"number" : "5.6.8",
"build_hash" : "688ecce",
"build_date" : "2018‐02‐16T16:46:30.010Z",
"build_snapshot" : false,
"lucene_version" : "6.6.1"
},
"tagline" : "You Know, for Search"
}
Postman調(diào)用RestAPI
####### 例如我們要?jiǎng)?chuàng)建一個(gè)叫articleindex的索引 ,就以put方式提交
http://127.0.0.1:9200/articleindex/
####### 新建文檔
以post方式提交 http://127.0.0.1:9200/articleindex/article
body:
{
"name" : "uV2glMR",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "RdV7UTQZT1‐Jnka9dDPsFg",
"version" : {
"number" : "5.6.8",
"build_hash" : "688ecce",
"build_date" : "2018‐02‐16T16:46:30.010Z",
"build_snapshot" : false,
"lucene_version" : "6.6.1"
},
"tagline" : "You Know, for Search"
}
{
"title":"SpringBoot2.0",
"content":"發(fā)布啦"
}
返回結(jié)果如下:
{
"_index": "articleindex",
"_type": "article",
"_id": "AWPKsdh0FdLZnId5S_F9",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
查詢?nèi)课臋n
####### 查詢某索引某類型的全部數(shù)據(jù),以get方式請求
http://127.0.0.1:9200/articleindex/article/_search 返回結(jié)果如下:
{
"_index": "articleindex",
"_type": "article",
"_id": "AWPKsdh0FdLZnId5S_F9",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
北京市昌平區(qū)建材城西路金燕龍辦公樓一層 電話:400-618-9090
2.2.4 修改文檔
以put形式提交以下地址:
{
"took": 5,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 2,
"max_score": 1,
"hits": [
{
"_index": "articleindex",
"_type": "article",
"_id": "AWPKrI4pFdLZnId5S_F7",
"_score": 1,
"_source": {
"title": "SpringBoot2.0",
"content": "發(fā)布啦"
}
},
{
"_index": "articleindex",
"_type": "article",
"_id": "AWPKsdh0FdLZnId5S_F9",
"_score": 1,
"_source": {
"title": "elasticsearch入門",
"content": "零基礎(chǔ)入門"
}
}
]
}
}
修改文檔 以put方式提交
http://192.168.184.134:9200/articleindex/article/AWPKrI4pFdLZnId5S_F7
body:
返回結(jié)果:
如果我們在地址中的ID不存在,則會(huì)創(chuàng)建新文檔
以put形式提交以下地址:
http://192.168.184.134:9200/articleindex/article/1
body:
返回信息:
{
"title":"SpringBoot2.0正式版",
"content":"發(fā)布了嗎"
}
{
"_index": "articleindex",
"_type": "article",
"_id": "AWPKsdh0FdLZnId5S_F9",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": false
}
{
"title":"十次方課程好給力",
"content":"知識(shí)點(diǎn)很多"
}
北京市昌平區(qū)建材城西路金燕龍辦公樓一層 電話:400-618-9090
再次查詢,看是否有新增的這條文檔
2.2.5 按ID查詢文檔
GET方式請求
http://192.168.184.134:9200/articleindex/article/1
2.2.6 基本匹配查詢
根據(jù)某列進(jìn)行查詢 get方式提交下列地址:
http://192.168.184.134:9200/articleindex/article/_search?q=title:十次方課程
好給力
以上為按標(biāo)題查詢,返回結(jié)果如下:
{
"_index": "articleindex",
"_type": "article",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"created": true
}
按ID查詢文檔 GET方式請求
http://192.168.184.134:9200/articleindex/article/1
基本匹配查詢 根據(jù)某列進(jìn)行查詢 get方式提交下列地址:
http://192.168.184.134:9200/articleindex/article/_search?q=title:十次方課程
好給力
按標(biāo)題查詢結(jié)果如下
{
"took": 10,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 2.0649285,
"hits": [
{
"_index": "articleindex",
"_type": "article",
"_id": "1",
"_score": 2.0649285,
"_source": {
"title": "十次方課程好給力",
"content": "知識(shí)點(diǎn)很多"
}
}
]
}
}
模糊查詢 我們可以用*代表任意字符
http://192.168.184.134:9200/articleindex/article/_search?q=title:*s*
刪除文檔 根據(jù)ID刪除文檔,刪除ID為1的文檔 DELETE方式提交
http://192.168.184.134:9200/articleindex/article/1
返回結(jié)果如下:
{
"found": true,
"_index": "articleindex",
"_type": "article",
"_id": "1",
"_version": 2,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
}
}
Head插件的安裝與使用
通過rest請求的方式使用Elasticsearch,未免太過麻煩,而且也不夠人性化。我
們一般都會(huì)使用圖形化界面來實(shí)現(xiàn)Elasticsearch的日常管理,最常用的就是Head插件
步驟1:
下載head插件:https://github.com/mobz/elasticsearch-head
配套資料中已提供。 elasticsearch-head-master.zip
步驟2:
解壓到任意目錄,但是要和elasticsearch的安裝目錄區(qū)別開。
步驟3:
安裝node js ,安裝cnpm
npm install ‐g cnpm ‐‐registry=https://registry.npm.taobao.org //如安裝過,跳過
步驟4:
將grunt安裝為全局命令 。Grunt是基于Node.js的項(xiàng)目構(gòu)建工具。它可以自動(dòng)運(yùn)行你所
設(shè)定的任務(wù)
步驟5:安裝依賴
cnpm install
步驟6:
進(jìn)入head目錄啟動(dòng)head,在命令提示符下輸入命令
步驟7:
打開瀏覽器,輸入 http://localhost:9100
步驟8:
點(diǎn)擊連接按鈕沒有任何相應(yīng),按F12發(fā)現(xiàn)有如下錯(cuò)誤
No 'Access-Control-Allow-Origin' header is present on the requested resource
這個(gè)錯(cuò)誤是由于elasticsearch默認(rèn)不允許跨域調(diào)用,而elasticsearch-head是屬于前端工
程,所以報(bào)錯(cuò)。
我們這時(shí)需要修改elasticsearch的配置,讓其允許跨域訪問。
修改elasticsearch配置文件:elasticsearch.yml,增加以下兩句命令:
此步為允許elasticsearch跨越訪問 點(diǎn)擊連接即可看到相關(guān)信息
npm install ‐g grunt‐cli
grunt server
http.cors.enabled: true
http.cors.allow‐origin: "*"
此步為允許elasticsearch跨越訪問 點(diǎn)擊連接即可看到相關(guān)信息
Head插件操作
新建索引
選擇“索引”選項(xiàng)卡,點(diǎn)擊“新建索引”按鈕,輸入索引名稱點(diǎn)擊OK
新建或修改文檔
在復(fù)合查詢中提交地址,輸入內(nèi)容,提交方式為PUT,點(diǎn)擊數(shù)據(jù)瀏覽 ,點(diǎn)擊要查詢的索引名稱,右側(cè)窗格中顯示文檔信息
點(diǎn)擊文檔信息:
修改數(shù)據(jù)后重新提交請求 , 此時(shí)因?yàn)镮D已經(jīng)存在,所以執(zhí)行的是修改操作。
重新查詢此記錄,發(fā)現(xiàn)版本為2 。也就是說每次修改后版本都會(huì)增加1.
刪除文檔
DELETE方式提交,帶上ID號(hào)
IK分詞器
我們在瀏覽器地址欄輸入http://127.0.0.1:9200/_analyze?
analyzer=chinese&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" : 2,
"end_offset" : 3,
"type" : "<IDEOGRAPHIC>",
"position" : 2
},
{
"token" : "序",
"start_offset" : 3,
"end_offset" : 4,
"type" : "<IDEOGRAPHIC>",
"position" : 3
},
{
"token" : "員",
"start_offset" : 4,
"end_offset" : 5,
"type" : "<IDEOGRAPHIC>",
"position" : 4
}
]
}
默認(rèn)的中文分詞是將每個(gè)字看成一個(gè)詞,這顯然是不符合要求的,所以我們需要安裝中
文分詞器來解決這個(gè)問題。
IK分詞器安裝
下載地址:https://github.com/medcl/elasticsearch-analysis-ik/releases 下載5.6.8版
本 課程配套資源也提供了: 資源\配套軟件\elasticsearch\elasticsearch-analysis-ik-
5.6.8.zip
(1)先將其解壓,將解壓后的elasticsearch文件夾重命名文件夾為ik
(2)將ik文件夾拷貝到elasticsearch/plugins 目錄下。
(3)重新啟動(dòng),即可加載IK分詞器
IK分詞器測試
IK提供了兩個(gè)分詞算法ik_smart 和 ik_max_word
其中 ik_smart 為最少切分,ik_max_word為最細(xì)粒度劃分
(1)最小切分:在瀏覽器地址欄輸入地址
http://127.0.0.1:9200/_analyze?analyzer=ik_smart&pretty=true&text=我是程序員
{
"tokens" : [
{
"token" : "我",
"start_offset" : 0,
"end_offset" : 1,
"type" : "CN_CHAR",
"position" : 0
},
{
"token" : "是",
"start_offset" : 1,
"end_offset" : 2,
"type" : "CN_CHAR",
"position" : 1
},
{
"token" : "程序員",
"start_offset" : 2,
"end_offset" : 5,
"type" : "CN_WORD",
"position" : 2
}
]
}
(2)最細(xì)切分:在瀏覽器地址欄輸入地址
http://127.0.0.1:9200/_analyze?analyzer=ik_max_word&pretty=true&text=我是程序
員
{
"tokens" : [
{
"token" : "我",
"start_offset" : 0,
"end_offset" : 1,
"type" : "CN_CHAR",
"position" : 0
},
{
"token" : "是",
"start_offset" : 1,
"end_offset" : 2,
"type" : "CN_CHAR",
"position" : 1
},
{
"token" : "程序員",
"start_offset" : 2,
"end_offset" : 5,
"type" : "CN_WORD",
"position" : 2
},
{
"token" : "程序",
"start_offset" : 2,
"end_offset" : 4,
"type" : "CN_WORD",
"position" : 3
},
{
"token" : "員",
"start_offset" : 4,
"end_offset" : 5,
"type" : "CN_CHAR",
"position" : 4
}
]
}
默認(rèn)的分詞并沒有識(shí)別“傳智播客”是一個(gè)詞。如果我們想讓系統(tǒng)識(shí)別“傳智播客”是一個(gè)
詞,需要編輯自定義詞庫。
步驟:
(1)進(jìn)入elasticsearch/plugins/ik/config目錄
(2)新建一個(gè)my.dic文件,編輯內(nèi)容:
法師打發(fā)時(shí)光
修改IKAnalyzer.cfg.xml(在ik/config目錄下)
<properties>
<comment>IK Analyzer 擴(kuò)展配置</comment>
<!‐‐用戶可以在這里配置自己的擴(kuò)展字典 ‐‐>
<entry key="ext_dict">my.dic</entry>
<!‐‐用戶可以在這里配置自己的擴(kuò)展停止詞字典‐‐>
<entry key="ext_stopwords"></entry>
</properties>
重新啟動(dòng)elasticsearch,通過瀏覽器測試分詞效果
{
"tokens" : [
{
"token" : "傳智播客",
"start_offset" : 0,
"end_offset" : 4,
"type" : "CN_WORD",
"position" : 0
}
]
}
示列:搜索微服務(wù)開發(fā)
1,導(dǎo)入pom.xml依賴
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring‐data‐elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>com.tensquare</groupId>
<artifactId>tensquare_common</artifactId>
<version>1.0‐SNAPSHOT</version>
</dependency>
</dependencies>
2,application.yml
server:
port: 9007
spring:
application:
name: tensquare‐search #指定服務(wù)名
data:
elasticsearch:
cluster‐nodes: 127.0.0.1:9300
創(chuàng)建實(shí)體類
/**
* 文章實(shí)體類
*/
@Document(indexName="tensquare",type="article")
public class Article implements Serializable{
@Id
private String id;//ID
@Field(index= true
,analyzer="ik_max_word",searchAnalyzer="ik_max_word")
private String title;//標(biāo)題
@Field(index= true
,analyzer="ik_max_word",searchAnalyzer="ik_max_word")
private String content;//文章正文
private String state;//審核狀態(tài)
//getter and setter ......
}
controller
@RestController
@CrossOrigin
@RequestMapping("/article")
public class ArticleSearchController {
@Autowired
private ArticleSearchService articleSearchService;
@RequestMapping(method= RequestMethod.POST)
public Result save(@RequestBody Article article){
articleSearchService.save(article);
return new Result(true, StatusCode.OK, "操作成功");
}
}
ArticleSearchRepository新增方法定義 dao
/**
* 檢索
* @param
* @return
*/
public Page<Article> findByTitleOrContentLike(String title, String
content, Pageable pageable);
ArticleSearchService新增方法
public Page<Article> findByTitleLike(String keywords, int page, int size)
{
PageRequest pageRequest = PageRequest.of(page‐1, size);
return
articleSearchRepository.findByTitleOrContentLike(keywords,keywords,
pageRequest);
}
ArticleSearchController方法
@RequestMapping(value="/search/{keywords}/{page}/{size}",method=
RequestMethod.GET)
public Result findByTitleLike(@PathVariable String keywords,
@PathVariable int page, @PathVariable int size){
Page<Article> articlePage =
articleSearchService.findByTitleLike(keywords,page,size);
return new Result(true, StatusCode.OK, "查詢成功",
new PageResult<Article>(articlePage.getTotalElements(),
articlePage.getContent()));
}
elasticsearch與MySQL數(shù)據(jù)同步 Logstash
Logstash是一款輕量級(jí)的日志搜集處理框架,可以方便的把分散的、多樣化的日志搜集
起來,并進(jìn)行自定義的處理,然后傳輸?shù)街付ǖ奈恢?,比如某個(gè)服務(wù)器或者文件。
解壓,進(jìn)入bin目錄
logstash ‐e 'input { stdin { 輸入什么} } output { stdout {輸出什么} }'
stdin,表示輸入流,指從鍵盤輸入
stdout,表示輸出流,指從顯示器輸出
命令行參數(shù):
-e 執(zhí)行
--config 或 -f 配置文件,后跟參數(shù)類型可以是一個(gè)字符串的配置或全路徑文件名或全路徑
路徑(如:/etc/logstash.d/,logstash會(huì)自動(dòng)讀取/etc/logstash.d/目錄下所有*.conf 的文
本文件,然后在自己內(nèi)存里拼接成一個(gè)完整的大配置文件再去執(zhí)行)
MySQL數(shù)據(jù)導(dǎo)入Elasticsearch
(1)在logstash-5.6.8安裝目錄下創(chuàng)建文件夾mysqletc (名稱隨意)
(2)文件夾下創(chuàng)建mysql.conf (名稱隨意) ,內(nèi)容如下:
(3)將mysql驅(qū)動(dòng)包mysql-connector-java-5.1.46.jar拷貝至D:/logstash-
5.6.8/mysqletc/ 下 。D:/logstash-5.6.8是你的安裝目錄
(4)命令行下執(zhí)行
logstash ‐f ../mysqletc/mysql.conf
觀察控制臺(tái)輸出,每間隔1分鐘就執(zhí)行一次sql查詢。
再次刷新elasticsearch-head的數(shù)據(jù)顯示,看是否也更新了數(shù)據(jù)。
Elasticsearch Docker環(huán)境下安裝
(1)下載鏡像 docker pull elasticsearch:5.6.8
(2)創(chuàng)建容器
docker run ‐di ‐‐name=tensquare_elasticsearch ‐p 9200:9200 ‐p 9300:9300
elasticsearch:5.6.8
(3)瀏覽器輸入地址:http://192.168.184.134:9200/ 即可看到如下信息
{
"name" : "WmBn0H‐",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "2g‐VVbm9Rty7J4sksZNJEg",
"version" : {
"number" : "5.6.8",
"build_hash" : "688ecce",
"build_date" : "2018‐02‐16T16:46:30.010Z",
"build_snapshot" : false,
"lucene_version" : "6.6.1"
},
"tagline" : "You Know, for Search"
}
(4) 修改demo的application.yml
spring:
data:
elasticsearch:
cluster‐nodes: 192.168.184.135:930
(5)運(yùn)行測試程序,發(fā)現(xiàn)會(huì)報(bào)如下錯(cuò)誤 這是因?yàn)閑lasticsearch從5版本以后默認(rèn)不開啟遠(yuǎn)程連接,需要修改配置文件
NoNodeAvailableException[None of the configured nodes are available:
[{#transport#‐1}{exvgJLR‐RlCNMJy‐hzKtnA}{192.168.184.135}
{192.168.184.135:9300}]
]
at
org.elasticsearch.client.transport.TransportClientNodesService.ensureNodes
AreAvailable(TransportClientNodesService.java:347)
at
org.elasticsearch.client.transport.TransportClientNodesService.execute(Tra
nsportClientNodesService.java:245)
at
org.elasticsearch.client.transport.TransportProxyClient.execute(TransportP
roxyClient.java:59)
(6) 進(jìn)入容器 docker exec ‐it tensquare_elasticsearch /bin/bash
我們看到elasticsearch所在的目錄為/usr/share/elasticsearch ,進(jìn)入config看到了
配置文件 elasticsearch.yml 無法使用 vi進(jìn)行編輯
(7)拷貝配置文件到宿主機(jī)
首先退出容器(將容器中的文件拷貝出去修改),然后執(zhí)行命令:
docker cp
tensquare_elasticsearch:/usr/share/elasticsearch/config/elasticsearch.yml
/usr/share/elasticsearch.yml
(8)停止和刪除原來創(chuàng)建的容器
docker stop tensquare_elasticsearch
docker rm tensquare_elasticsearch
(9)重新執(zhí)行創(chuàng)建容器命令
docker run ‐di ‐‐name=tensquare_elasticsearch ‐p 9200:9200 ‐p 9300:9300 ‐v
/usr/share/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch
.yml elasticsearch:5.6.8
(10)修改/usr/share/elasticsearch.yml 將 transport.host: 0.0.0.0 前的#去掉后保
存文件退出。其作用是允許任何ip地址訪問elasticsearch .開發(fā)測試階段可以這么做,生
產(chǎn)環(huán)境下指定具體的IP
(11)重啟啟動(dòng) docker restart tensquare_elasticsearch
重啟后發(fā)現(xiàn)重啟啟動(dòng)失敗了,這時(shí)什么原因呢?這與我們剛才修改的配置有關(guān),因?yàn)?br>
elasticsearch在啟動(dòng)的時(shí)候會(huì)進(jìn)行一些檢查,比如最多打開的文件的個(gè)數(shù)以及虛擬內(nèi)存
區(qū)域數(shù)量等等,如果你放開了此配置,意味著需要打開更多的文件以及虛擬內(nèi)存,所以
我們還需要系統(tǒng)調(diào)優(yōu)。
(12)系統(tǒng)調(diào)優(yōu) 修改/etc/security/limits.conf ,追加內(nèi)容
* soft nofile 65536
* hard nofile 65536
nofile是單個(gè)進(jìn)程允許打開的最大文件個(gè)數(shù) soft nofile 是軟限制 hard nofile是硬限制
修改/etc/sysctl.conf,追加內(nèi)容
vm.max_map_count=655360
限制一個(gè)進(jìn)程可以擁有的VMA(虛擬內(nèi)存區(qū)域)的數(shù)量
執(zhí)行下面命令 修改內(nèi)核參數(shù)馬上生效
sysctl ‐p
(13)重新啟動(dòng)虛擬機(jī),再次啟動(dòng)容器,發(fā)現(xiàn)已經(jīng)可以啟動(dòng)并遠(yuǎn)程訪問
IK分詞器安裝
(1)快捷鍵alt+p進(jìn)入sftp , 將ik文件夾上傳至宿主機(jī)
(2)在宿主機(jī)中將ik文件夾拷貝到容器內(nèi) /usr/share/elasticsearch/plugins 目錄下。
docker cp ik tensquare_elasticsearch:/usr/share/elasticsearch/plugins/
(3)重新啟動(dòng),即可加載IK分詞器
docker restart tensquare_elasticsearch
HEAD插件安裝 (圖形化操作界面)
(1)修改/usr/share/elasticsearch.yml ,添加允許跨域配置
http.cors.enabled: true
http.cors.allow‐origin: "*"
(2)重新啟動(dòng)elasticseach容器
(3)下載head鏡像
docker pull mobz/elasticsearch‐head:5
(4)創(chuàng)建head容器
docker run ‐di ‐‐name=myhead ‐p 9100:9100 docker pull mobz/elasticsearch‐
head:5