DBA Elasticsearch 嵌套查询
内嵌文档
以下是一个嵌套文档案例:
PUT /test_index/userinfo/1?pretty
{
"name" : "Jack",
"age" : 18,
"gender" : 1,
"hobby" : ["篮球", "足球", "音乐"],
"class" : {
"name" : "三年级一班",
"principal" : "王老师",
"number_of_people" : 30
},
"grades":{
"MySQL" : 89,
"MongoDB" : 62,
"Redis" : 38,
"Elasticsearch": 92
}
}
查询是三年级的文档,将会搜索出该文档:
GET /test_index/userinfo/_search
{
"query": {
"match": {
"class.name": "三年级"
}
}
}
内嵌文档的关键词必须严格大小写,如下所示:
GET /test_index/userinfo/_search
{
"query":{
"match":{
"name":"jack"
}
},
"_source": ["grades.MySQL", "grades.MongoDB"]
}
内嵌数组
或者查询hobby中具有足球或者唱歌的文档,该文档也会被检索到,相当于IN:
GET /test_index/userinfo/_search
{
"query": {
"match": {
"hobby": "足球 音乐"
}
}
}
数组嵌文档
现在再插入一条数据,这种数据类型常用于多关系展示,如一对多、多对多关系:
PUT /test_index/userinfo/2
{
"name" : "Ken",
"grades" : [
{"type":"MySQL","grades":70},
{"type":"MongoDB","grades":92},
{"type":"Redis","grades":87}
]
}
其实查询时同普通内嵌文档一样,直接.后面需要拿的字段即可:
GET /test_index/userinfo/_search
{
"query": {
"match": {
"name": "KEN"
}
},
"_source": ["grades.type","grades.grades"]
}
# 结果
"grades" : [
{
"grades" : 70,
"type" : "MySQL"
},
{
"grades" : 92,
"type" : "MongoDB"
},
{
"grades" : 87,
"type" : "Redis"
}
]
它在内部会经过一次处理,将所有数组中的对象value处理为数组element,如下:
{
"grades.type" : ["MySQL","MongoDB","Redis"],
"grades.grades" : [70, 92, 87]
}