一 序
本文屬於Elasticsearch核心技術與實戰學習筆記系列。
二 如何顯示定義一個 Mapping
2.1自定義 Mapping 的一些建議
爲了減少輸入的工作量,減少出錯率,依照以下步驟
- 創建一個臨時的 index,寫入一些樣本數據
- 通過訪問 Mapping API 獲得該臨時文件的動態 Mapping 定義
- 修改後用,使用該配置創建的索引
- 刪除臨時索引
2.2控制當前字段是否被索引
index - 控制當前字段是否被索引。默認爲 true。如果設置成 false,該字段不可被搜索。
demo :
DELETE users
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"
}
POST /users/_search
{
"query": {
"match": {
"mobile":"12345678"
}
}
}
結果異常:
"caused_by": {
"type": "illegal_argument_exception",
"reason": "Cannot search on field [mobile] since it is not indexed."
}
Index Options
四種不同級別的 Index Options 配置,可以控制倒排索引記錄的內容
- docs - 記錄 doc id
- freqs - 記錄 doc id 和 term frequencies
- positions - 記錄 doc id /term frequencies /term position
- offsets - doc id / term frequencies / term posistion / character offects
Text 類型默認記錄 postions,其他默認爲 docs
記錄內容越多,佔用存儲空間越大
null_value
- 需要對 NULL 值實現搜索
- 只有 Keyword 類型支持設定 Null_Value
#設定Null_value
DELETE users
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"
}
}
}
返回數據:
"hits" : [
{
"_index" : "users",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.2876821,
"_source" : {
"firstName" : "Ruan",
"lastName" : "Yiming",
"mobile" : null
}
}
]
copy_to
- _all 在 7 中已經被 copy_to 所替代
- 滿足一些特定的搜索需求
- copy_to 將字段的數值拷貝到目標字段,實現類似 _all 的作用
- copy_to 的目標字段不出現在_source 中
demo:
#設置 Copy to
DELETE users
PUT users
{
"mappings": {
"properties": {
"firstName":{
"type": "text",
"copy_to": "fullName"
},
"lastName":{
"type": "text",
"copy_to": "fullName"
}
}
}
}
PUT users/_doc/1
{
"firstName":"Ruan",
"lastName": "Yiming"
}
GET users/_search?q=fullName:(Ruan Yiming)
查詢中的fullName,source字段中沒有fullName,copy_to起到作用,
"hits" : [
{
"_index" : "users",
"_type" : "_doc",
"_id" : "1",
"_score" : 0.5753642,
"_source" : {
"firstName" : "Ruan",
"lastName" : "Yiming"
}
}
]
數組類型
- Elasticsearch 中不提供專門的數組類型。但是任何字段,都可以包含多個相同類型的數值
#數組類型
PUT users/_doc/1
{
"name":"onebird",
"interests":"reading"
}
PUT users/_doc/1
{
"name":"twobirds",
"interests":["reading","music"]
}
POST users/_search
{
"query": {
"match_all": {}
}
}
查看搜索結果:
再看看看mapping:
GET users/_mapping