Elasticsearch-基礎

一些概念

索引-index:

一個索引就是一個擁有幾分相似特征的文檔的集合。比如說,你可以有一個客戶數據的索引,另一個產品目錄的索引,還有一個訂單數據的索引。一個索引由一個名字來標識(必須全部是小寫字母的),并且當我們要對對應于這個索引中的文檔進行索引、搜索、更新和刪除的時候,都要使用到這個名字

類型-type:

一個類型是你的索引的一個邏輯上的分類/分區,其語義完全由你來定。通常,會為具有一組共同字段的文檔定義一個類型。比如說,我們假設你運營一個博客平臺并且將你所有的數據存儲到一個索引中。在這個索引中,你可以為用戶數據定義一個類型,為博客數據定義另一個類型

文檔-document:

一個文檔是一個可被索引的基礎信息單元。比如,你可以擁有某一個客戶的文檔,某一個產品的一個文檔,當然,也可以擁有某個訂單的一個文檔。文檔以JSON(Javascript Object Notation)格式來表示

分片和復制-shard&replicas:

CURL操作

健康檢查: curl 'localhost:9200/_cat/health?v'

[root@localhost bin]#  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
1487839064 16:37:44  elk     yellow          1         1     16  16    0    0       16             0                  -                 50.0%

注:status:綠色代表一切正常(集群功能齊全),黃色意味著所有的數據都是可用的,但是某些復制沒有被分配(集群功能齊全),紅色則代表因為某些原因,某些數據不可用

節點查詢:curl 'localhost:9200/_cat/nodes?v'

[root@localhost bin]# curl 'localhost:9200/_cat/nodes?v'
ip            heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name
172.16.24.105           45          59   1    0.00    0.01     0.05 mdi       *      node-jimmy

索引列表: curl 'localhost:9200/_cat/indices?v'

[root@localhost bin]#  curl 'localhost:9200/_cat/indices?v'
health status index                       uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   megacorp                    nh2ECFHoSJe5mcJinMT16A   5   1          5            0     27.8kb         27.8kb

注:pri:5個主分片,rep:1個復制,docs.count:5個文檔

索引創建: curl -XPUT 'localhost:9200/customer?pretty'

[root@localhost bin]#   curl -XPUT 'localhost:9200/customer?pretty'
{
  "acknowledged" : true,
  "shards_acknowledged" : true
}

索引刪除: curl -XDELETE 'localhost:9200/customer?pretty'

[root@localhost ~]#   curl -XDELETE 'localhost:9200/customer?pretty'
{
  "acknowledged" : true
}

文檔創建: curl -XPUT 'localhost:9200/customer/external/1?pretty' -d ' {"name": "John Doe"}'

注:為了索引一個文檔,我們必須告訴Elasticsearch這個文檔要到這個索引的哪個類型(type)下
示例:將一個簡單客戶文檔索引到customer索引、“external”類型中,這個文檔的ID是1

[root@localhost bin]# curl -XPUT 'localhost:9200/customer/external/1?pretty' -d ' {"name": "John Doe"}'
{
  "_index" : "customer",
  "_type" : "external",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "created" : true
}

注: 不指定id的時候,使用POST,elasticsearch會自動生成一個ID
curl -XPOST 'localhost:9200/customer/external?pretty' -d ' {"name": "Jane Doe" }'

文檔查詢: curl -XGET 'localhost:9200/customer/external/1?pretty'

[root@localhost ~]#   curl -XGET 'localhost:9200/customer/external/1?pretty'
{
  "_index" : "customer",
  "_type" : "external",
  "_id" : "1",
  "_version" : 1,
  "found" : true,
  "_source" : {
    "name" : "John Doe"
  }
}

文檔更新:curl -XPUT 'localhost:9200/customer/external/1?pretty' -d ' { "name": "Jane Doe" }'

[root@localhost ~]#  curl -XPUT 'localhost:9200/customer/external/1?pretty' -d '  {  "name": "Jane Doe"  }'
{
  "_index" : "customer",
  "_type" : "external",
  "_id" : "1",
  "_version" : 2,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "created" : false
}
[root@localhost ~]# curl 'localhost:9200/_cat/indices?v'
health status index                       uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   customer                    AYGh32xWQSC3D6OWIwiVyQ   5   1          1            0        7kb            7kb
[root@localhost ~]# 

注:version變成了2,docs.count個數沒有變化

文檔刪除-單個: curl -XDELETE 'localhost:9200/customer/external/2?pretty'

注:指定刪除的ID

[root@localhost ~]#  curl -XDELETE 'localhost:9200/customer/external/2?pretty'
{
  "found" : true,
  "_index" : "customer",
  "_type" : "external",
  "_id" : "2",
  "_version" : 3,
  "result" : "deleted",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  }
}

文檔刪除-多個:
curl -XDELETE 'localhost:9200/customer/external/_query?pretty' -d '
{
"query": { "match": { "name": "John Doe" } }
}'

注:首先查詢出所有name為John Doe的,然后一起刪除

文檔批處理-創建:創建一個Id為21和22的文檔
curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"index":{"_id":"21"}}
{"name": "John Doe" }
{"index":{"_id":"22"}}
{"name": "Jane Doe" } '

[root@localhost ~]#  curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
>         {"index":{"_id":"21"}}
>         {"name": "John Doe" }
>         {"index":{"_id":"22"}}
>         {"name": "Jane Doe" }
>         '
{
  "took" : 35,
  "errors" : false,
  "items" : [
    {
      "index" : {
        "_index" : "customer",
        "_type" : "external",
        "_id" : "21",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "created" : true,
        "status" : 201
      }
    },
    {
      "index" : {
        "_index" : "customer",
        "_type" : "external",
        "_id" : "22",
        "_version" : 1,
        "result" : "created",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "created" : true,
        "status" : 201
      }
    }
  ]
}

文檔批處理:一個更新,一個刪除
curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
{"update":{"_id":"21"}}
{"doc": { "name": "Jimmy" } }
{"delete":{"_id":"22"}}
'

[root@localhost ~]#  curl -XPOST 'localhost:9200/customer/external/_bulk?pretty' -d '
>         {"update":{"_id":"21"}}
>         {"doc": { "name": "Jimmy" } }
>         {"delete":{"_id":"22"}}
>         '
{
  "took" : 29,
  "errors" : false,
  "items" : [
    {
      "update" : {
        "_index" : "customer",
        "_type" : "external",
        "_id" : "21",
        "_version" : 2,
        "result" : "updated",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "status" : 200
      }
    },
    {
      "delete" : {
        "found" : true,
        "_index" : "customer",
        "_type" : "external",
        "_id" : "22",
        "_version" : 2,
        "result" : "deleted",
        "_shards" : {
          "total" : 2,
          "successful" : 1,
          "failed" : 0
        },
        "status" : 200
      }
    }
  ]
}

*注: bulk API按順序執行這些動作。如果其中一個動作因為某些原因失敗了,將會繼續處理它后面的動作。當bulk API返回時,它將提供每個動作的狀態(按照同樣的順序),所以你能夠看到某個動作成功與否。

示例

https://github.com/bly2k/files/blob/master/accounts.zip?raw=true 下載數據樣本,解壓上傳并導入ES

curl -XPOST 'localhost:9200/bank/account/_bulk?pretty' --data-binary @/usr/share/elasticsearch/accounts.json


查詢API:_search

注:有兩種基本的方式來運行搜索:一種是在REST請求的URI中發送搜索參數,另一種是將搜索參數發送到REST請求體中。請求體方法的表達能力更好,并且你可以使用更加可讀的JSON格式來定義搜索。

① 加參數方式:curl 'localhost:9200/bank/_search?q=*&pretty' 返回bank索引中的所有的文檔

注:_search:在bank索引中搜索,q=參數指示Elasticsearch去匹配這個索引中所有的文檔*

[root@localhost ~]#     curl 'localhost:9200/bank/_search?q=*&pretty'
{
  "took" : 40,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1000,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "bank",
        "_type" : "account",
        "_id" : "25",
        "_score" : 1.0,
        "_source" : {
          "account_number" : 25,
          "balance" : 40540,
          "firstname" : "Virginia",
          "lastname" : "Ayala",
          "age" : 39,
          "gender" : "F",
          "address" : "171 Putnam Avenue",
          "employer" : "Filodyne",
          "email" : "virginiaayala@filodyne.com",
          "city" : "Nicholson",
          "state" : "PA"
        }
      },
   ,

返回參數說明:

   - took —— Elasticsearch執行這個搜索的耗時,以毫秒為單位
   - timed_out —— 指明這個搜索是否超時
   - _shards —— 指出多少個分片被搜索了,同時也指出了成功/失敗的被搜索的shards的數量
   - hits —— 搜索結果
   - hits.total —— 能夠匹配我們查詢標準的文檔的總數目
   - hits.hits —— 真正的搜索結果數據(默認只顯示前10個文檔)
   - _score和max_score —— 現在先忽略這些字段           

②方法體方式: curl -XPOST 'localhost:9200/bank/_search?pretty' -d '{"query": { "match_all": {} } }'

注:query部分告訴我查詢的定義,match_all部分就是我們想要運行的查詢的類型。match_all查詢,就是簡單地查詢一個指定索引下的所有的文檔。

除了query參數,還可以指定其他參數:
1.size:返回多少條數據,不指定默認為10
[root@localhost ~]#  curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
        {
          "query": { "match_all": {} },
          "size": 1
        }'

2.from:返回第11到第20個文檔,不指定默認為0,與size結合使用分頁
[root@localhost ~]#  curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
         {
          "query": { "match_all": {} },
          "from": 10,
          "size": 10
        }'

3.sort:排序,賬戶余額降序排序,返回前10個
[root@localhost ~]#    curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
        {
          "query": { "match_all": {} },
          "sort": { "balance": { "order": "desc" } }
        }'

4._source:指定返回字段,此例子只返回account_number和balance
[root@localhost ~]#   curl -XGET 'localhost:9200/bank/_search?pretty' -d '
         {
           "query": { "match_all": {} },
           "_source": ["account_number", "balance"]
         }'
{
  "took" : 25,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1000,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "bank",
        "_type" : "account",
        "_id" : "25",
        "_score" : 1.0,
        "_source" : {
          "account_number" : 25,
          "balance" : 40540
        }
   }

5.match:指定匹配字段查詢,此例返回賬戶編號為20的文檔
[root@localhost ~]# curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
         {
          "query": { "match": { "account_number": 20 } }
         }'
match:此例返回地址中包含“mill”或者包含“lane”的賬戶
[root@localhost ~]# curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
        {
          "query": { "match": { "address": "mill lane" } }
        }' 

6.match_phrase:此例匹配短語“mill lane”,此時只會查詢出address為mill lane的文檔
[root@localhost ~]#   curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
        {
          "query": { "match_phrase": { "address": "mill lane" } }
        }'
7. bool:布爾查詢
bool must語句指明對于一個文檔,所有的查詢都必須為真,這個文檔才能夠匹配成功
此例查詢返回包含“mill”和“lane”的所有的賬戶
[root@localhost ~]#    curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
         {
           "query": {
             "bool": {
               "must": [
                 { "match": { "address": "mill" } },
                 { "match": { "address": "lane" } }
               ]
             }
           }
        }'
bool should語句指明對于一個文檔,查詢列表中,只要有一個查詢匹配,那么這個文檔就被看成是匹配的
此例查詢返回包含“mill”或“lane”的所有的賬戶
[root@localhost ~]#    curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
         {
           "query": {
             "bool": {
               "should": [
                 { "match": { "address": "mill" } },
                 { "match": { "address": "lane" } }
               ]
             }
           }
         }'
bool must_not語句指明對于一個文檔,查詢列表中的所有查詢都必須都不為真,這個文檔才被認為是匹配的
[root@localhost ~]#  curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
         {
           "query": {
             "bool": {
               "must_not": [
                 { "match": { "address": "mill" } },
                 { "match": { "address": "lane" } }
               ]
             }
           }
         }'
可以在一個bool查詢里一起使用must、should、must_not
此例返回40歲以上并且不生活在ID(daho)的人的賬戶
[root@localhost ~]#   curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
         {
           "query": {
             "bool": {
               "must": [
                 { "match": { "age": "40" } }
               ],
               "must_not": [
                 { "match": { "state": "ID" } }
               ]
             }
           }
         }'

過濾器

先前搜索結果中的_score字段這個得分是與我們指定的搜索查詢匹配程度的一個相對度量。得分越高,文檔越相關,得分越低文檔的相關度越低。
Elasticsearch中的所有的查詢都會觸發相關度得分的計算。對于那些我們不需要相關度得分的場景下,Elasticsearch以過濾器的形式提供了另一種查詢功能。
過濾器在概念上類似于查詢,但是它們有非常快的執行速度,這種快的執行速度主要有以下兩個原因

  • 過濾器不會計算相關度的得分,所以它們在計算上更快一些
  • 過濾器可以被緩存到內存中,這使得在重復的搜索查詢上,其要比相應的查詢快出許多
此例返回balance在【20000,30000】之間的賬戶
curl -XGET "http://localhost:9200/bank/_search" -d'
{
  "query": {
    "bool": {
      "must": { "match_all": {} },
      "filter": {
        "range": {
          "balance": {
            "gte": 20000,
            "lte": 30000
          }
        }
      }
    }
  }
}'
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容