Elasticsearch-基礎(chǔ)

一些概念

索引-index:

一個索引就是一個擁有幾分相似特征的文檔的集合太援。比如說掌桩,你可以有一個客戶數(shù)據(jù)的索引沮明,另一個產(chǎn)品目錄的索引,還有一個訂單數(shù)據(jù)的索引誊册。一個索引由一個名字來標識(必須全部是小寫字母的)领突,并且當我們要對對應(yīng)于這個索引中的文檔進行索引、搜索案怯、更新和刪除的時候君旦,都要使用到這個名字

類型-type:

一個類型是你的索引的一個邏輯上的分類/分區(qū),其語義完全由你來定嘲碱。通常于宙,會為具有一組共同字段的文檔定義一個類型。比如說悍汛,我們假設(shè)你運營一個博客平臺并且將你所有的數(shù)據(jù)存儲到一個索引中捞魁。在這個索引中,你可以為用戶數(shù)據(jù)定義一個類型离咐,為博客數(shù)據(jù)定義另一個類型

文檔-document:

一個文檔是一個可被索引的基礎(chǔ)信息單元谱俭。比如,你可以擁有某一個客戶的文檔宵蛀,某一個產(chǎn)品的一個文檔昆著,當然,也可以擁有某個訂單的一個文檔术陶。文檔以JSON(Javascript Object Notation)格式來表示

分片和復(fù)制-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:綠色代表一切正常(集群功能齊全)凑懂,黃色意味著所有的數(shù)據(jù)都是可用的,但是某些復(fù)制沒有被分配(集群功能齊全)梧宫,紅色則代表因為某些原因接谨,某些數(shù)據(jù)不可用

節(jié)點查詢: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個復(fù)制塘匣,docs.count:5個文檔

索引創(chuàng)建: 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
}

文檔創(chuàng)建: 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個數(shù)沒有變化

文檔刪除-單個: 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的笤闯,然后一起刪除

文檔批處理-創(chuàng)建:創(chuàng)建一個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按順序執(zhí)行這些動作棍厂。如果其中一個動作因為某些原因失敗了颗味,將會繼續(xù)處理它后面的動作。當bulk API返回時勋桶,它將提供每個動作的狀態(tài)(按照同樣的順序)脱衙,所以你能夠看到某個動作成功與否侥猬。

示例

https://github.com/bly2k/files/blob/master/accounts.zip?raw=true 下載數(shù)據(jù)樣本,解壓上傳并導(dǎo)入ES

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


查詢API:_search

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

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

注:_search:在bank索引中搜索,q=參數(shù)指示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"
        }
      },
   ,

返回參數(shù)說明:

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

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

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

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

2.from:返回第11到第20個文檔辫封,不指定默認為0硝枉,與size結(jié)合使用分頁
[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”或者包含“l(fā)ane”的賬戶
[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”和“l(fā)ane”的所有的賬戶
[root@localhost ~]#    curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
         {
           "query": {
             "bool": {
               "must": [
                 { "match": { "address": "mill" } },
                 { "match": { "address": "lane" } }
               ]
             }
           }
        }'
bool should語句指明對于一個文檔拓劝,查詢列表中雏逾,只要有一個查詢匹配,那么這個文檔就被看成是匹配的
此例查詢返回包含“mill”或“l(fā)ane”的所有的賬戶
[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" } }
               ]
             }
           }
         }'

過濾器

先前搜索結(jié)果中的_score字段這個得分是與我們指定的搜索查詢匹配程度的一個相對度量。得分越高侨把,文檔越相關(guān)犀变,得分越低文檔的相關(guān)度越低。
Elasticsearch中的所有的查詢都會觸發(fā)相關(guān)度得分的計算秋柄。對于那些我們不需要相關(guān)度得分的場景下获枝,Elasticsearch以過濾器的形式提供了另一種查詢功能。
過濾器在概念上類似于查詢骇笔,但是它們有非呈〉辏快的執(zhí)行速度嚣崭,這種快的執(zhí)行速度主要有以下兩個原因

  • 過濾器不會計算相關(guān)度的得分,所以它們在計算上更快一些
  • 過濾器可以被緩存到內(nèi)存中懦傍,這使得在重復(fù)的搜索查詢上雹舀,其要比相應(yīng)的查詢快出許多
此例返回balance在【20000,30000】之間的賬戶
curl -XGET "http://localhost:9200/bank/_search" -d'
{
  "query": {
    "bool": {
      "must": { "match_all": {} },
      "filter": {
        "range": {
          "balance": {
            "gte": 20000,
            "lte": 30000
          }
        }
      }
    }
  }
}'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市粗俱,隨后出現(xiàn)的幾起案子说榆,更是在濱河造成了極大的恐慌,老刑警劉巖寸认,帶你破解...
    沈念sama閱讀 206,482評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件签财,死亡現(xiàn)場離奇詭異,居然都是意外死亡偏塞,警方通過查閱死者的電腦和手機唱蒸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,377評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來灸叼,“玉大人油宜,你說我怎么就攤上這事×耍” “怎么了慎冤?”我有些...
    開封第一講書人閱讀 152,762評論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長沧卢。 經(jīng)常有香客問我蚁堤,道長,這世上最難降的妖魔是什么但狭? 我笑而不...
    開封第一講書人閱讀 55,273評論 1 279
  • 正文 為了忘掉前任披诗,我火速辦了婚禮,結(jié)果婚禮上立磁,老公的妹妹穿的比我還像新娘呈队。我一直安慰自己,他們只是感情好唱歧,可當我...
    茶點故事閱讀 64,289評論 5 373
  • 文/花漫 我一把揭開白布宪摧。 她就那樣靜靜地躺著,像睡著了一般颅崩。 火紅的嫁衣襯著肌膚如雪几于。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,046評論 1 285
  • 那天沿后,我揣著相機與錄音沿彭,去河邊找鬼。 笑死尖滚,一個胖子當著我的面吹牛喉刘,可吹牛的內(nèi)容都是我干的瞧柔。 我是一名探鬼主播,決...
    沈念sama閱讀 38,351評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼睦裳,長吁一口氣:“原來是場噩夢啊……” “哼造锅!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起推沸,我...
    開封第一講書人閱讀 36,988評論 0 259
  • 序言:老撾萬榮一對情侶失蹤备绽,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后鬓催,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體肺素,經(jīng)...
    沈念sama閱讀 43,476評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,948評論 2 324
  • 正文 我和宋清朗相戀三年宇驾,在試婚紗的時候發(fā)現(xiàn)自己被綠了倍靡。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,064評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡课舍,死狀恐怖塌西,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情筝尾,我是刑警寧澤捡需,帶...
    沈念sama閱讀 33,712評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站筹淫,受9級特大地震影響站辉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜损姜,卻給世界環(huán)境...
    茶點故事閱讀 39,261評論 3 307
  • 文/蒙蒙 一饰剥、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧摧阅,春花似錦汰蓉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,264評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至娇跟,卻和暖如春岩齿,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背苞俘。 一陣腳步聲響...
    開封第一講書人閱讀 31,486評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留龄章,地道東北人吃谣。 一個月前我還...
    沈念sama閱讀 45,511評論 2 354
  • 正文 我出身青樓乞封,卻偏偏與公主長得像,于是被迫代替她去往敵國和親岗憋。 傳聞我的和親對象是個殘疾皇子肃晚,可洞房花燭夜當晚...
    茶點故事閱讀 42,802評論 2 345

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