Elasticsearch學習筆記(一) DSL語句
阿新 • • 發佈:2018-11-08
1. index
1.1 查詢所有index
GET /_cat/indices?v
1.2 新增index
#新增一個名為pigg的index
PUT /pigg
1.3 刪除index
#刪除pigg這個index,產線千萬別這麼做,刪了就完了
DELETE /pigg
2. document
2.1 新增document
PUT /pigg/_doc/1
{
"name": "三爺",
"age": 29,
"hometown": "鹽城",
"gender": "male"
}
PUT /pigg/_doc/2
{
"name": "珣爺",
"age": 28,
"hometown": "徐州",
"gender": "female"
}
PUT /pigg/_doc/3
{
"name": "米可",
"age": 1,
"hometown": "蘇州",
"gender": "female"
}
2.2 查詢document
2.2.1 查詢index的所有document
GET /pigg/_search
2.2.1 根據id查詢document
GET /pigg/_doc/1?pretty
返回結果:
{
"_index": "pigg",
"_type" : "_doc",
"_id": "1",
"_version": 4,
"found": true,
"_source": {
"name": "三爺",
"age": 29,
"hometown": "鹽城",
"gender": "male"
}
}
2.2.2 用sort排序查詢
#對age進行倒序查詢
GET /pigg/_search
{
"query": {"match_all": {}},
"sort": [
{
"age": {
"order": "desc"
}
}
]
}
2.2.3 用from和size分頁查詢
#查詢前2條資料, from是從0開始的
GET /pigg/_search
{
"query": {"match_all": {}},
"sort": [
{
"age": {
"order": "desc"
}
}
],
"from": 0,
"size": 2
}
2.3 修改document
2.3.1 用put替換document
查詢當前pigg表裡id=1的文件
GET /pigg/_doc/1?pretty
返回如下:
{
"_index": "pigg",
"_type": "_doc",
"_id": "1",
"_version": 4,
"found": true,
"_source": {
"name": "三爺",
"age": 29,
"hometown": "鹽城",
"gender": "male"
}
}
用put方式更新id=1的文件
PUT /pigg/_doc/1
{
"name": "鹽城三爺"
}
再次查詢id=1的文件
{
"_index": "pigg",
"_type": "_doc",
"_id": "1",
"_version": 5,
"found": true,
"_source": {
"name": "鹽城三爺"
}
}
通過上面發現用put是替換了整個文件,而不是更新name這一個欄位
2.3.2 用post更新document
先恢復id=1的文件為一開始的資料,然後執行如下語句
修改name,並新增interesting這個欄位
POST /pigg/_doc/1/_update?pretty
{
"doc":{
"name": "鹽城鼕鼕",
"interesting": "watching TV"
}
}
再次查詢id=1的文件
{
"_index": "pigg",
"_type": "_doc",
"_id": "1",
"_version": 8,
"found": true,
"_source": {
"name": "鹽城鼕鼕",
"age": 29,
"hometown": "鹽城",
"gender": "male",
"interesting": "watching TV"
}
}
這時發現用post更新的是文件的區域性欄位,原來有的欄位更新,沒有的欄位則新增這個欄位
2.3.3 用script更新document
查詢當前id=1的人的age是29,現在要對age加1
POST /pigg/_doc/1/_update
{
"script": "ctx._source.age += 1"
}
再次查詢id=1的文件,發現age已經是30了
{
"_index": "pigg",
"_type": "_doc",
"_id": "1",
"_version": 9,
"found": true,
"_source": {
"name": "鹽城鼕鼕",
"age": 30,
"hometown": "鹽城",
"gender": "male",
"interesting": "watching TV"
}
}
2.4 刪除document
DELETE /pigg/_doc/1