多值字段,在一般開發情況下,我們想讓某個字段包含多個字段,我們可以通過一個标簽數組來代替單一字元串,
{“tags”:[“boy”, “monitor”]};
對于數組不需要特殊的映射,任何一個字段可以包括零個、一個或者多個值,對于全文字段而言将被解析成多個詞。數組裡面的值的類型必須是同樣的,es将使用數組的第一個詞類型來确定這個字段的類型
下面貼上es的字段類型圖和數組類型的使用執行個體。
首先 我們建立一個帶有數組類型的mapping。
curl -H "Content-Type: application/json" -XPUT 'http://xxxxxxxx:9200/school/' -d '
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
},
"mappings": {
"student": {
"properties": {
"name": {
"index": "true",
"type": "keyword"
},
"age": {
"type": "integer"
},
"tags": {
"index": "true",
"type": "keyword"
}
}
}
}
}'
然後我們建立幾個測試的文檔:
PUT /school/student/1/_create
{
"name": "李小二",
"age": 17,
"tags": [
"father",
"player"
]
}
PUT /school/student/2/_create
{
"name": "張三豐",
"age": 18,
"tags": [
"boy",
"monitor"
]
}
PUT /school/student/3/_create
{
"name": "王小強",
"age": 19,
"tags": [
"cool",
"player"
]
}
好了,我們建立了三個文檔,
下面我們搜尋一下看看呢?
{
"query": {
"match_all": {}
}
}
針對tags字段搜尋:
{
"query": {
"term": {
"tags": "player"
}
}
}
如果查詢整個字段多個值相等,需要用bool-must文法來确定
{
"query": {
"bool": {
"must": [
{
"term": {
"tags": "player"
}
},
{
"term": {
"tags": "cool"
}
}
]
}
}
}
祝好運!