1. 程式人生 > 實用技巧 >ES基礎(四十六)Elasticsearch 資料建模最佳實踐

ES基礎(四十六)Elasticsearch 資料建模最佳實踐

課程demo

###### Cookie Service

##索引資料,dynamic mapping 會不斷加入新增欄位
PUT cookie_service/_doc/1
{
 "url":"www.google.com",
 "cookies":{
   "username":"tom",
   "age":32
 }
}

PUT cookie_service/_doc/2
{
 "url":"www.amazon.com",
 "cookies":{
   "login":"2019-01-01",
   
"email":"[email protected]" } } DELETE cookie_service #使用 Nested 物件,增加key/value PUT cookie_service { "mappings": { "properties": { "cookies": { "type": "nested", "properties": { "name": { "type": "keyword" }, "dateValue": {
"type": "date" }, "keywordValue": { "type": "keyword" }, "IntValue": { "type": "integer" } } }, "url": { "type": "text", "fields": { "keyword": { "type": "keyword",
"ignore_above": 256 } } } } } } ##寫入資料,使用key和合適型別的value欄位 PUT cookie_service/_doc/1 { "url":"www.google.com", "cookies":[ { "name":"username", "keywordValue":"tom" }, { "name":"age", "intValue":32 } ] } PUT cookie_service/_doc/2 { "url":"www.amazon.com", "cookies":[ { "name":"login", "dateValue":"2019-01-01" }, { "name":"email", "IntValue":32 } ] } # Nested 查詢,通過bool查詢進行過濾 POST cookie_service/_search { "query": { "nested": { "path": "cookies", "query": { "bool": { "filter": [ { "term": { "cookies.name": "age" }}, { "range":{ "cookies.intValue":{ "gte":30 } } } ] } } } } } # 在Mapping中加入元資訊,便於管理 PUT softwares/ { "mappings": { "_meta": { "software_version_mapping": "1.0" } } } GET softwares/_mapping PUT softwares/_doc/1 { "software_version":"7.1.0" } DELETE softwares # 優化,使用inner object PUT softwares/ { "mappings": { "_meta": { "software_version_mapping": "1.1" }, "properties": { "version": { "properties": { "display_name": { "type": "keyword" }, "hot_fix": { "type": "byte" }, "marjor": { "type": "byte" }, "minor": { "type": "byte" } } } } } } #通過 Inner Object 寫入多個文件 PUT softwares/_doc/1 { "version":{ "display_name":"7.1.0", "marjor":7, "minor":1, "hot_fix":0 } } PUT softwares/_doc/2 { "version":{ "display_name":"7.2.0", "marjor":7, "minor":2, "hot_fix":0 } } PUT softwares/_doc/3 { "version":{ "display_name":"7.2.1", "marjor":7, "minor":2, "hot_fix":1 } } # 通過 bool 查詢, POST softwares/_search { "query": { "bool": { "filter": [ { "match":{ "version.marjor":7 } }, { "match":{ "version.minor":2 } } ] } } } # Not Null 解決聚合的問題 DELETE ratings PUT ratings { "mappings": { "properties": { "rating": { "type": "float", "null_value": 1.0 } } } } PUT ratings/_doc/1 { "rating":5 } PUT ratings/_doc/2 { "rating":null } POST ratings/_search POST ratings/_search { "size": 0, "aggs": { "avg": { "avg": { "field": "rating" } } } } POST ratings/_search { "query": { "term": { "rating": { "value": 1 } } } }