1)環境準備
啓動Elasticsearch https://blog.csdn.net/qq_36918149/article/details/104221934
啓動Kinbana https://blog.csdn.net/qq_36918149/article/details/104224625
2)如何定義一個Mappin?
PUT users_test
{
"mappings": {
"properties": {
#firstName 爲字段名稱
"firstName":{
# type 定索引類型
"type": "text"
}
}
}
}
3)自定義Mapping比較好的實踐經驗
4)控制字段是否被索引
#刪除索引,否則在設置索引的時候會報錯,提示索引已經設置
DELETE users
# 設置mobile字段不能被索引
PUT users
{
"mappings" : {
"properties" : {
"firstName" : {
"type" : "text"
},
"lastName" : {
"type" : "text"
},
"mobile" : {
"type" : "text",
"index": false
}
}
}
}
#存條數據到對應的索引中,備後面流程驗證索引是否生效
PUT users/_doc/1
{
"firstName":"Ruan",
"lastName": "Yiming",
"mobile": "12345678"
}
#驗證通過mobile 查詢數據爲空,表示不能被索引
POST /users/_search
{
"query": {
"match": {
"mobile":"12345678"
}
}
}
#驗證結果,從結果中可以看出,用沒有索引的字段查詢, 會報錯
5)控制倒排索引內容(Index Options )
備註:通過控制索引級別,實現控制倒排索引的內容
6)null 也可以被索引(null_value)
#刪除 索引以免在設置mapping的時候異常
DELETE users
#設置mapping,並設置mobile字段爲null依然可以被索引
PUT users
{
"mappings" : {
"properties" : {
"firstName" : {
"type" : "text"
},
"lastName" : {
"type" : "text"
},
"mobile" : {
"type" : "keyword",
"null_value": "NULL"
}
}
}
}
#錄入數據,以便驗證
PUT users/_doc/1
{
"firstName":"Ruan",
"lastName": "Yiming",
"mobile": null
}
PUT users/_doc/2
{
"firstName":"Ruan2",
"lastName": "Yiming2"
}
#驗證
GET users/_search
{
"query": {
"match": {
"mobile":"NULL"
}
}
}
#驗證結果, 可以看出,字段爲null 值的時候依然可以被,索引查詢到結果
7)組合索引(copy_to)
#刪除 索引以免在設置mapping的時候異常
DELETE users
#構建組合索引 fullName
PUT users
{
"mappings": {
"properties": {
"firstName":{
"type": "text",
"copy_to": "fullName"
},
"lastName":{
"type": "text",
"copy_to": "fullName"
}
}
}
}
#寫入驗證數據
PUT users/_doc/1
{
"firstName":"Ruan",
"lastName": "Yiming"
}
#驗證
#組合索引用法1
GET users/_search?q=fullName:(Ruan Yiming)
#組合索引用法2
POST users/_search
{
"query": {
"match": {
"fullName":{
"query": "Ruan Yiming",
"operator": "and"
}
}
}
}
結果中可以看出,組合索引已經生效
8) 數組類型的索引
#寫入一個數組數據
PUT users/_doc/1
{
"name":"twobirds",
"interests":["reading","music"]
}
#查看數組寫入情況
GET users/_doc/1
#從下圖結果中可以看出,數組已經寫入成功
#查看一下,此時mapping 情況,從下圖結果中可以看出,mapping的類型還是text類型
9)總結
- Mapping設置設置以後,不能修改, 所以在設置前一定要規劃好對應的索引結構。
- 本文中講述的mapping設置其實偏重於一些特殊的場景, 常規mapping直接用默認的即可。