官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/7.2/array.html。
在 ES 中,没有专用的数组类型,任何字段都可以变成数组。
示例:
创建索引:
PUT student
{
"mappings" : {
"properties" : {
"scores" : {
"type" : "integer"
}
}
}
}
使用 _bulk
创建文档,注意,文档2的 scores 是数组:
POST _bulk
{ "index" : { "_index" : "student", "_id" : "1" } }
{ "scores" : 80 }
{ "index" : { "_index" : "student", "_id" : "2" } }
{ "scores" : [80, 90] }
查询所有数据:
# 请求
GET student/_search
# 响应
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "student",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"scores" : 80
}
},
{
"_index" : "student",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"scores" : [
80,
90
]
}
}
]
}
}
在查询时,命中数组的其中一个,就会认为是符合条件:
# 请求
GET student/_search
{
"query": {
"term": {
"scores": 90
}
}
}
# 响应
{
"took" : 487,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "student",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"scores" : [
80,
90
]
}
}
]
}
}
如何为文档1的scores字段添加一个值 ?可以这样:
POST student/_update_by_query
{
"query": {
"match": {
"_id": 1
}
},
"script": {
"source": "if (ctx._source.containsKey(\"scores\")) {if (ctx._source.scores instanceof List) ctx._source.scores.add(88); else ctx._source.scores = [ctx._source.scores, 88];} else {ctx._source.scores = [88]}"
}
}
执行后重新查询:
# 请求
GET student/_search
# 响应
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "student",
"_type" : "_doc",
"_id" : "2",
"_score" : 1.0,
"_source" : {
"scores" : [
80,
90
]
}
},
{
"_index" : "student",
"_type" : "_doc",
"_id" : "1",
"_score" : 1.0,
"_source" : {
"scores" : [
80,
88
]
}
}
]
}
}
关于 script 语法的介绍:
- https://www.elastic.co/guide/en/elasticsearch/reference/7.2/modules-scripting.html
- https://www.elastic.co/guide/en/elasticsearch/painless/7.2/painless-lang-spec.html