多值字段,在一般开发情况下,我们想让某个字段包含多个字段,我们可以通过一个标签数组来代替单一字符串,
{“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"
}
}
]
}
}
}
祝好运!