Elasticsearch快速入門,掌握這些剛恰好!

SpringBoot實戰電商項目mall(30k+star)地址:github.com/macrozheng/…html

摘要

記得剛接觸Elasticsearch的時候,沒找啥資料,直接看了遍Elasticsearch的中文官方文檔,中文文檔好久沒更新了,一直都是2.3的版本。最近又從新看了遍6.0的官方文檔,因爲官方文檔介紹的內容比較多,每次看都很費力,因此此次整理了其中最經常使用部分,寫下了這篇入門教程,但願對你們有所幫助。node

簡介

Elasticsearch是一個基於Lucene的搜索服務器。它提供了一個分佈式的全文搜索引擎,基於restful web接口。Elasticsearch是用Java語言開發的,基於Apache協議的開源項目,是目前最受歡迎的企業搜索引擎。Elasticsearch普遍運用於雲計算中,可以達到實時搜索,具備穩定,可靠,快速的特色。git

安裝

Windows下的安裝

Elasticsearch

  • 安裝中文分詞插件,在elasticsearch-6.2.2\bin目錄下執行如下命令;
elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.2.2/elasticsearch-analysis-ik-6.2.2.zip
複製代碼

  • 運行bin目錄下的elasticsearch.bat啓動Elasticsearch;

Kibana

  • 運行bin目錄下的kibana.bat,啓動Kibana的用戶界面

Linux下的安裝

Elasticsearch

  • 下載elasticsearch 6.4.0的docker鏡像;
docker pull elasticsearch:6.4.0
複製代碼
  • 修改虛擬內存區域大小,不然會由於太小而沒法啓動;
sysctl -w vm.max_map_count=262144
複製代碼
  • 使用docker命令啓動;
docker run -p 9200:9200 -p 9300:9300 --name elasticsearch \
-e "discovery.type=single-node" \
-e "cluster.name=elasticsearch" \
-v /mydata/elasticsearch/plugins:/usr/share/elasticsearch/plugins \
-v /mydata/elasticsearch/data:/usr/share/elasticsearch/data \
-d elasticsearch:6.4.0
複製代碼
  • 啓動時會發現/usr/share/elasticsearch/data目錄沒有訪問權限,只須要修改該目錄的權限,再從新啓動便可;
chmod 777 /mydata/elasticsearch/data/
複製代碼
  • 安裝中文分詞器IKAnalyzer,並從新啓動;
docker exec -it elasticsearch /bin/bash
#此命令須要在容器中運行
elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.4.0/elasticsearch-analysis-ik-6.4.0.zip
docker restart elasticsearch
複製代碼

Kibina

  • 下載kibana 6.4.0的docker鏡像;
docker pull kibana:6.4.0
複製代碼
  • 使用docker命令啓動;
docker run --name kibana -p 5601:5601 \
--link elasticsearch:es \
-e "elasticsearch.hosts=http://es:9200" \
-d kibana:6.4.0
複製代碼

相關概念

  • Near Realtime(近實時):Elasticsearch是一個近乎實時的搜索平臺,這意味着從索引文檔到可搜索文檔之間只有一個輕微的延遲(一般是一秒鐘)。
  • Cluster(集羣):羣集是一個或多個節點的集合,它們一塊兒保存整個數據,並提供跨全部節點的聯合索引和搜索功能。每一個羣集都有本身的惟一羣集名稱,節點經過名稱加入羣集。
  • Node(節點):節點是指屬於集羣的單個Elasticsearch實例,存儲數據並參與集羣的索引和搜索功能。能夠將節點配置爲按集羣名稱加入特定集羣,默認狀況下,每一個節點都設置爲加入一個名爲elasticsearch的羣集。
  • Index(索引):索引是一些具備類似特徵的文檔集合,相似於MySql中數據庫的概念。
  • Type(類型):類型是索引的邏輯類別分區,一般,爲具備一組公共字段的文檔類型,相似MySql中表的概念。注意:在Elasticsearch 6.0.0及更高的版本中,一個索引只能包含一個類型。
  • Document(文檔):文檔是可被索引的基本信息單位,以JSON形式表示,相似於MySql中行記錄的概念。
  • Shards(分片):當索引存儲大量數據時,可能會超出單個節點的硬件限制,爲了解決這個問題,Elasticsearch提供了將索引細分爲分片的概念。分片機制賦予了索引水平擴容的能力、並容許跨分片分發和並行化操做,從而提升性能和吞吐量。
  • Replicas(副本):在可能出現故障的網絡環境中,須要有一個故障切換機制,Elasticsearch提供了將索引的分片複製爲一個或多個副本的功能,副本在某些節點失效的狀況下提供高可用性。

集羣狀態查看

  • 查看集羣健康狀態;
GET /_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
1585552862 15:21:02  elasticsearch yellow          1         1     27  27    0    0       25             0                  -                 51.9%
複製代碼
  • 查看節點狀態;
GET /_cat/nodes?v
複製代碼
ip        heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name
127.0.0.1           23          94  28                          mdi       *      KFFjkpV
複製代碼
  • 查看全部索引信息;
GET /_cat/indices?v
複製代碼
health status index    uuid                   pri rep docs.count docs.deleted store.size pri.store.size
green  open   pms      xlU0BjEoTrujDgeL6ENMPw   1   0         41            0     30.5kb         30.5kb
green  open   .kibana  ljKQtJdwT9CnLrxbujdfWg   1   0          2            1     10.7kb         10.7kb
複製代碼

索引操做

  • 建立索引並查看;
PUT /customer
GET /_cat/indices?v
複製代碼
health status index    uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   customer 9uPjf94gSq-SJS6eOuJrHQ   5   1          0            0       460b           460b
green  open   pms      xlU0BjEoTrujDgeL6ENMPw   1   0         41            0     30.5kb         30.5kb
green  open   .kibana  ljKQtJdwT9CnLrxbujdfWg   1   0          2            1     10.7kb         10.7kb
複製代碼
  • 刪除索引並查看;
DELETE /customer
GET /_cat/indices?v
複製代碼
health status index    uuid                   pri rep docs.count docs.deleted store.size pri.store.size
green  open   pms      xlU0BjEoTrujDgeL6ENMPw   1   0         41            0     30.5kb         30.5kb
green  open   .kibana  ljKQtJdwT9CnLrxbujdfWg   1   0          2            1     10.7kb         10.7kb
複製代碼

類型操做

  • 查看文檔的類型;
GET /bank/account/_mapping
複製代碼
{
  "bank": {
    "mappings": {
      "account": {
        "properties": {
          "account_number": {
            "type": "long"
          },
          "address": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "age": {
            "type": "long"
          },
          "balance": {
            "type": "long"
          },
          "city": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "email": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "employer": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "firstname": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "gender": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "lastname": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "state": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    }
  }
}
複製代碼

文檔操做

  • 在索引中添加文檔;
PUT /customer/doc/1
{
  "name": "John Doe"
}
複製代碼
{
  "_index": "customer",
  "_type": "doc",
  "_id": "1",
  "_version": 1,
  "result": "created",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 3,
  "_primary_term": 1
}
複製代碼
  • 查看索引中的文檔;
GET /customer/doc/1
複製代碼
{
  "_index": "customer",
  "_type": "doc",
  "_id": "1",
  "_version": 2,
  "found": true,
  "_source": {
    "name": "John Doe"
  }
}
複製代碼
  • 修改索引中的文檔:
POST /customer/doc/1/_update
{
  "doc": { "name": "Jane Doe" }
}
複製代碼
{
  "_index": "customer",
  "_type": "doc",
  "_id": "1",
  "_version": 2,
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 4,
  "_primary_term": 1
}
複製代碼
  • 刪除索引中的文檔;
DELETE /customer/doc/1
複製代碼
{
  "_index": "customer",
  "_type": "doc",
  "_id": "1",
  "_version": 3,
  "result": "deleted",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 2,
  "_primary_term": 1
}
複製代碼
  • 對索引中的文檔執行批量操做;
POST /customer/doc/_bulk
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
複製代碼
{
  "took": 45,
  "errors": false,
  "items": [
    {
      "index": {
        "_index": "customer",
        "_type": "doc",
        "_id": "1",
        "_version": 3,
        "result": "updated",
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "_seq_no": 5,
        "_primary_term": 1,
        "status": 200
      }
    },
    {
      "index": {
        "_index": "customer",
        "_type": "doc",
        "_id": "2",
        "_version": 1,
        "result": "created",
        "_shards": {
          "total": 2,
          "successful": 1,
          "failed": 0
        },
        "_seq_no": 0,
        "_primary_term": 1,
        "status": 201
      }
    }
  ]
}
複製代碼

數據搜索

查詢表達式(Query DSL)是一種很是靈活又富有表現力的查詢語言,Elasticsearch使用它能夠以簡單的JSON接口來實現豐富的搜索功能,下面的搜索操做都將使用它。github

數據準備

  • 首先咱們須要導入必定量的數據用於搜索,使用的是銀行帳戶表的例子,數據結構以下:
{
    "account_number": 0,
    "balance": 16623,
    "firstname": "Bradshaw",
    "lastname": "Mckenzie",
    "age": 29,
    "gender": "F",
    "address": "244 Columbus Place",
    "employer": "Euron",
    "email": "bradshawmckenzie@euron.com",
    "city": "Hobucken",
    "state": "CO"
}
複製代碼
  • 咱們先複製下須要導入的數據,數據地址: github.com/macrozheng/…web

  • 而後直接使用批量操做來導入數據,注意本文全部操做都在Kibana的Dev Tools中進行;docker

POST /bank/account/_bulk
{
  "index": {
    "_id": "1"
  }
}
{
  "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"
}
......省略若干條數據
複製代碼

  • 導入完成後查看索引信息,能夠發現bank索引中已經建立了1000條文檔。
GET /_cat/indices?v
複製代碼
health status index    uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   bank     HFjxDLNLRA-NATPKUQgjBw   5   1       1000            0    474.6kb        474.6kb
複製代碼

搜索入門

  • 最簡單的搜索,使用match_all來表示,例如搜索所有;
GET /bank/_search
{
  "query": { "match_all": {} }
}
複製代碼

  • 分頁搜索,from表示偏移量,從0開始,size表示每頁顯示的數量;
GET /bank/_search
{
  "query": { "match_all": {} },
  "from": 0,
  "size": 10
}
複製代碼

  • 搜索排序,使用sort表示,例如按balance字段降序排列;
GET /bank/_search
{
  "query": { "match_all": {} },
  "sort": { "balance": { "order": "desc" } }
}
複製代碼

  • 搜索並返回指定字段內容,使用_source表示,例如只返回account_numberbalance兩個字段內容:
GET /bank/_search
{
  "query": { "match_all": {} },
  "_source": ["account_number", "balance"]
}
複製代碼

條件搜索

  • 條件搜索,使用match表示匹配條件,例如搜索出account_number20的文檔:
GET /bank/_search
{
  "query": {
    "match": {
      "account_number": 20
    }
  }
}
複製代碼

  • 文本類型字段的條件搜索,例如搜索address字段中包含mill的文檔,對比上一條搜索能夠發現,對於數值類型match操做使用的是精確匹配,對於文本類型使用的是模糊匹配;
GET /bank/_search
{
  "query": {
    "match": {
      "address": "mill"
    }
  },
  "_source": [
    "address",
    "account_number"
  ]
}
複製代碼

  • 短語匹配搜索,使用match_phrase表示,例如搜索address字段中同時包含milllane的文檔:
GET /bank/_search
{
  "query": {
    "match_phrase": {
      "address": "mill lane"
    }
  }
}
複製代碼

組合搜索

  • 組合搜索,使用bool來進行組合,must表示同時知足,例如搜索address字段中同時包含milllane的文檔;
GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "address": "mill" } },
        { "match": { "address": "lane" } }
      ]
    }
  }
}
複製代碼

  • 組合搜索,should表示知足其中任意一個,搜索address字段中包含mill或者lane的文檔;
GET /bank/_search
{
  "query": {
    "bool": {
      "should": [
        { "match": { "address": "mill" } },
        { "match": { "address": "lane" } }
      ]
    }
  }
}
複製代碼

  • 組合搜索,must_not表示同時不知足,例如搜索address字段中不包含mill且不包含lane的文檔;
GET /bank/_search
{
  "query": {
    "bool": {
      "must_not": [
        { "match": { "address": "mill" } },
        { "match": { "address": "lane" } }
      ]
    }
  }
}
複製代碼

  • 組合搜索,組合mustmust_not,例如搜索age字段等於40state字段不包含ID的文檔;
GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "age": "40" } }
      ],
      "must_not": [
        { "match": { "state": "ID" } }
      ]
    }
  }
}
複製代碼

過濾搜索

  • 搜索過濾,使用filter來表示,例如過濾出balance字段在20000~30000的文檔;
GET /bank/_search
{
  "query": {
    "bool": {
      "must": { "match_all": {} },
      "filter": {
        "range": {
          "balance": {
            "gte": 20000,
            "lte": 30000
          }
        }
      }
    }
  }
}
複製代碼

搜索聚合

  • 對搜索結果進行聚合,使用aggs來表示,相似於MySql中的group by,例如對state字段進行聚合,統計出相同state的文檔數量;
GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "state.keyword"
      }
    }
  }
}
複製代碼

  • 嵌套聚合,例如對state字段進行聚合,統計出相同state的文檔數量,再統計出balance的平均值;
GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "state.keyword"
      },
      "aggs": {
        "average_balance": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}
複製代碼

  • 對聚合搜索的結果進行排序,例如按balance的平均值降序排列;
GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "state.keyword",
        "order": {
          "average_balance": "desc"
        }
      },
      "aggs": {
        "average_balance": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}
複製代碼

  • 按字段值的範圍進行分段聚合,例如分段範圍爲age字段的[20,30] [30,40] [40,50],以後按gender統計文檔個數和balance的平均值;
GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_age": {
      "range": {
        "field": "age",
        "ranges": [
          {
            "from": 20,
            "to": 30
          },
          {
            "from": 30,
            "to": 40
          },
          {
            "from": 40,
            "to": 50
          }
        ]
      },
      "aggs": {
        "group_by_gender": {
          "terms": {
            "field": "gender.keyword"
          },
          "aggs": {
            "average_balance": {
              "avg": {
                "field": "balance"
              }
            }
          }
        }
      }
    }
  }
}
複製代碼

參考資料

www.elastic.co/guide/en/el…數據庫

公衆號

mall項目全套學習教程連載中,關注公衆號第一時間獲取。json

公衆號圖片
相關文章
相關標籤/搜索