elasticsearch入門二-安裝
看完本章將了解以下幾點
Elasticsearch提供了一個簡單一致的REST API,用于管理您的集群以及索引和搜索數據。es提供Java, JavaScript, Go, .NET, PHP, Perl, Python or Ruby這些語言客戶端。
index(索引)- 相當于mysql中的數據庫,索引,由很多的Document組成
type(類型)- 相當于mysql中的一張表
document(文檔)- 相當于mysql中的一行(一條記錄),由很多的Field組成,是Index和Search的最小單位。
field(域)- 相當于mysql中的一列(一個字段),由很多的Term組成,包括name(String)、fieldsData(BytesRef)和type(FieldType)這3個屬性。
Term - 相當于mysql中的一列(一個字段)中存儲的一個具體內容,由很多的字節組成,可以分詞
Invert Index - 倒排索引,或者簡稱Index,通過Term可以查詢到擁有該Term的文檔。可以配置為是否分詞,如果分詞可以配置不同的分詞器。
節點 - 一個服務器,由一個名字來標識
集群 - 一個或多個節點組織在一起
分片 - 將一份數據劃分為多小份的能力,允許水平分割和擴展容量。多個分片可以響應請求,提高性能和吞吐量。
副本 - 復制數據,一個節點出問題時,其余節點可以頂上。

集群啟動并運行后,就可以為某些數據建立索引了。Elasticsearch有多種存入方式,但最終它們都做同樣的事情:將JSON文檔放入Elasticsearch索引中。案例使用curl進行操作,下面先介紹下curl命令
curl -X<VERB> '<PROTOCOL>://<HOST>:<PORT>/<PATH>?<QUERY_STRING>' -d '<BODY>'
VERB 適當的HTTP方法或動詞。例如,GET,POST, PUT,HEAD,或DELETE。
PROTOCOL 無論是http或https。如果您在Elasticsearch前面有一個HTTPS代理,或者您使用Elasticsearch安全功能來加密HTTP通信,請使用后者。
HOST Elasticsearch集群中任何節點的主機名。或者, localhost用于本地計算機上的節點。
PORT 運行Elasticsearch HTTP服務的端口,默認為9200。
PATH API端點,可以包含多個組件,例如 _cluster/stats或_nodes/stats/jvm。
QUERY_STRING 任何可選的查詢字符串參數。例如,?pretty 將漂亮地打印 JSON響應以使其更易于閱讀。
BODY JSON編碼的請求正文(如有必要)。
所有與es交互的操作均提供postman測試案例
鑒于cmd使用curl命令不方便,在此可以借助docker來操作
#下載docker鏡像,該鏡像包含基本常用命令
docker pull donch/net-tools
#啟動鏡像并進入容器
docker run -it --net host cd1 /bin/bash

curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "John Doe"
}
'
#響應結果
{
"_index" : "customer", #索引名
"_type" : "_doc", #類型
"_id" : "1", #主鍵(通過_id值(ES內部轉換成_uid)可以唯一在es中確定一個Doc)
"_version" : 1, #更新版本(保證對文檔的變更能以正確的順序執行,避免亂序造成的數據丟失)
"result" : "created", #操作類型
"_shards" : { #分片信息
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0, #任何類型的寫操作,包括index、create、update和Delete,都會生成一個_seq_no
"_primary_term" : 1 #和_seq_no一樣是一個整數,每當Primary Shard發生重新分配時,比如重啟,Primary選舉等,_primary_term會遞增1
}
命令中的accounts.json文件點我下載(注意文件末尾需要以換行符結束,windows即末尾是空行)
#批量插入
curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk?pretty&refresh" --data-binary "@accounts.json"
#查看
curl "localhost:9200/_cat/indices?v"
#響應結果
#集群狀態 狀態 索引名 索引uuid 主分片 副本 文檔數量 刪除文檔數 總存儲量 主分片存儲量
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
green open bank l7sSYV2cQXmu6_4rJWVIww 5 1 1000 0 128.6kb 128.6kb
PUT定義為冪等操作,所以更新/插入時必須指定id,重復執行相同命令內容不變,version _seq_no更新
curl -X PUT "localhost:9200/customer/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "John Doe"
}
'
#響應結果
{
"_index" : "customer",
"_type" : "_doc",
"_id" : "1",
"_version" : 23,
"result" : "updated",
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"_seq_no" : 29,
"_primary_term" : 3
}
POST不是冪等操作,因此POST可以不指定id,當不傳id時es將自動生成id,即數據會不斷增加;傳id時,效果同PUT
#插入數據(未指定id)
curl -X POST "localhost:9200/customer/_doc?pretty" -H 'Content-Type: application/json' -d'
{
"name": "John Doe"
}
'
#查看結果
curl -X GET "localhost:9200/customer/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_all": {} },
"from": 1,
"size": 3
}
'
#響應結果
{
"took": 6,#花費時長
"timed_out": false,#是否超時
"_shards": {#分片查找信息
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {#命中信息
"total": {
"value": 8,
"relation": "eq"
},
"max_score": 1,
"hits": [#命中文檔信息
{
"_index": "customer",
"_type": "_doc",
"_id": "NcePk3IBWT1mnviEpD7P",
"_score": 1,
"_source": {#命中文檔內容
"name": "John Doe"
}
},
{
"_index": "customer",
"_type": "_doc",
"_id": "NsePk3IBWT1mnviEzD7Z",
"_score": 1,
"_source": {
"name": "John Doe"
}
},
{
"_index": "customer",
"_type": "_doc",
"_id": "N8ePk3IBWT1mnviE2T5S",
"_score": 1,
"_source": {
"name": "John Doe"
}
}
]
}
}
函數介紹
query - 查詢條件
bool - 組合多個查詢條件must - 必須滿足must_not - 可以視為過濾器。它影響文件是否包含在結果中,但不會影響文件的評分方式。match - 必須匹配,查詢字段可分開搜索,如"address": "mill lane",將查詢address中有mill或者lanematch_phrase - 必須匹配,查詢字段作為短語搜索,如"address": "111 mill lane",將查詢address中有"mill lane"filter - 過濾器
range - 范圍#按條件分頁查詢,且字段排序、
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must": [
{ "match_phrase": { "address": "mill lane" } }
],
"must_not": [
{ "match": { "age": "40" } }
],
"filter": {
"range": {
"balance": {
"gte": 40000,
"lte": 50000
}
}
}
}
},
"sort": [
{ "account_number": "asc" }
],
"from": 0,
"size": 2
}
'
#搜索結果
{
"took": 21,#花費時長,毫秒
"timed_out": false,#是否有分片超時,若配置了超時時間,分片查找聚合返回未超時的結果,犧牲了部分準確性提高性能
"_shards": {#搜索了多少個分片,以及成功,失敗或跳過了多少個分片
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {#命中信息
"total": {
"value": 1,#找到了多少個匹配的文檔
"relation": "eq"
},
"max_score": null,#找到的最相關文件的分數
"hits": [#命中文檔信息
{
"_index": "bank",
"_type": "_doc",
"_id": "136",
"_score": null,#文檔的相關性得分(使用時不適用match_all)
"_source": {#命中文檔內容(field(域))
"account_number": 136,
"balance": 45801,
"firstname": "Winnie",
"lastname": "Holland",
"age": 38,
"gender": "M",
"address": "198 Mill Lane",
"employer": "Neteria",
"email": "winnieholland@neteria.com",
"city": "Urie",
"state": "IL"
},
"sort": [#文檔的排序位置(不按相關性得分排序時)
136
]
},
{
"_index": "bank",
"_type": "_doc",
"_id": "1",
"_score": null,
"_source": {
"account_number": 1,
"balance": 39225,
"firstname": "Amber",
"lastname": "Duke",
"age": 32,
"gender": "M",
"address": "880 Holmes Lane",
"employer": "Pyrami",
"email": "amberduke@pyrami.com",
"city": "Brogan",
"state": "IL"
},
"sort": [
1
]
}
]
}
}
es支持聚合分析,也支持結果緩存,前提是同時滿足以下規則(包括但不限于):
函數介紹
aggs - Aggregations(聚合函數)
terms - 分組,結果不完全準確,準確度/效率根據size/shard_size變化
size - 總查詢結果個數,由各分片查詢結果合并得來shard_size - 每個分片查詢個數,追求準確度應該調高該參數,同時性能降低,缺省為(size* 1.5 + 10)include - 包含該值的文檔,支持數組格式["mazda", "honda"],支持通配符(待補充)exclude - 排除包含該值的文檔missing - 缺省值,如"missing": "N/A"collect_mode - 子聚合算法,取值depth_first,breadth_first,缺省為深度優先avg - 平均值order - 排序stats - 統計extended_stats - 擴展統計sum - 求和max - 最大值min - 最小值cardinality - 求基數(去重求個數)percentile_ranks - 百分比min_doc_count - 最小的文檔數目,只有滿足這個參數要求的個數的詞條才會被記錄返回shard_min_doc_count - 同上,分片script - 腳本及自定義腳本#查詢40歲及其以上的用戶,再將結果按地區(state)分組并降序,查詢排名前2位地區(state)的用戶的賬戶余額(balance)平均值及統計
#group_by_state/average_balance/stats_balance均為自定義名稱
curl -X GET "localhost:9200/bank/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"query": {
"bool": {
"filter": {
"range": {
"age": {
"gte": 40
}
}
}
}
},
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword",
"order": {
"average_balance": "desc"
},
"size": 2,
"shard_size": 4
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
},
"stats_balance": {
"stats": {
"field": "balance"
}
}
}
}
}
}
'
#查詢結果
{
"took": 20,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 45,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {#聚合結果
"group_by_state": {#請求時定義的名稱
"doc_count_error_upper_bound": -1,#因分片聚合導致被遺漏的terms,可能的最大值
"sum_other_doc_count": 42,#這次聚合中沒有統計到的文檔數
"buckets": [#聚合結果信息
{
"key": "PA",
"doc_count": 1,#分組后數量,因分片聚合,所以不精確
"stats_balance": {#請求時定義的名稱
"count": 1,
"min": 49159,
"max": 49159,
"avg": 49159,
"sum": 49159
},
"average_balance": {#請求時定義的名稱
"value": 49159
}
},
{
"key": "KY",
"doc_count": 2,
"stats_balance": {
"count": 2,
"min": 47887,
"max": 48972,
"avg": 48429.5,
"sum": 96859
},
"average_balance": {
"value": 48429.5
}
}
]
}
}
}
#刪除指定id
curl -X DELETE "localhost:9200/customer/_doc/1?pretty"
#結果
{
"_index": "customer",
"_type": "_doc",
"_id": "1",
"_version": 2,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 2,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
#刪除指定索引
curl -X DELETE "localhost:9200/customer?pretty"
#結果
{
"acknowledged": true
}
#查看索引信息
curl "localhost:9200/_cat/indices?v"
#響應結果
#集群狀態 狀態 索引名 索引uuid 主分片 副本 文檔數量 刪除文檔數 總存儲量 主分片存儲量
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
green open bank l7sSYV2cQXmu6_4rJWVIww 5 1 1000 0 128.6kb 128.6kb
#查看集群狀態
curl "localhost:9200/_cat/health?v"
#響應結果
epoch timestamp cluster status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1591686205 07:03:25 es-docker-cluster green 3 3 4 2 0 0 0 0 - 100.0%
#查看字段含義
curl "localhost:9200/_cat/health?help"
#查看更多命令
curl http://localhost:9200/_cat