6

elasticsearch嵌套查询

 2 years ago
source link: https://wakzz.cn/2018/09/20/elasticsearch/%E5%B5%8C%E5%A5%97%E6%9F%A5%E8%AF%A2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

elasticsearch嵌套查询

祈雨的博客
2018-09-20
PUT /testindex/testtype/1
{
"group":"fans",
"users":[
{
"name":"name1",
"age":20
},
{
"name":"name2",
"age":26
}
]
}
PUT /testindex/testtype/2
{
"group":"fans",
"users":[
{
"name":"name2",
"age":15
},
{
"name":"name3",
"age":30
}
]
}

对于上述数据,通过普通查询方式查询users的结果会与预期不同。
例如如下的查询语句,预期只返回第一条数据,实际上两条数据全部返回。

GET /testindex/testtype/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"users.name": "name2"
}
},
{
"range": {
"users.age": {
"gte": 20
}
}
}
]
}
}
}

修改mapping

使用嵌套查询,需要制定mapping为nested。

PUT /testindex
{
"mappings": {
"testtype": {
"properties": {
"group": {
"type":"string"
},
"user": {
"type": "nested"
}
}
}
}
}
GET /testindex/testtype/_search
{
"query": {
"nested": {
"path": "users",
"query": {
"bool": {
"must": [
{
"match": {
"users.name": "name2"
}
},
{
"range": {
"users.age": {
"gte": 20
}
}
}
]
}
}
}
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK