ES学习和使用笔记之arrays of objects查询

来源:互联网 发布:克隆mac地址有什么坏处 编辑:程序博客网 时间:2024/05/22 06:40

ES中JSON文档在索引中被扁平化化的 键-值 形式。所以当出现json对象数组时,扁平化后失去关联性,示例如下
PUT /my_index/blogpost/1
{
“title”: “Nest eggs”,
“body”: “Making your money work…”,
“tags”: [ “cash”, “shares” ],
“comments”: [
{
“name”: “John Smith”,
“comment”: “Great article”,
“age”: 28,
“stars”: 4,
“date”: “2014-09-01”
},
{
“name”: “Alice White”,
“comment”: “More like this please”,
“age”: 31,
“stars”: 5,
“date”: “2014-10-22”
}
]
}
最终在索引中会变成如下(structured JSON document is flattened into a simple key-value format )
{
“title”: [ eggs, nest ],
“body”: [ making, money, work, your ],
“tags”: [ cash, shares ],
“comments.name”: [ alice, john, smith, white ],
“comments.comment”: [ article, great, like, more, please, this ],
“comments.age”: [ 28, 31 ],
“comments.stars”: [ 4, 5 ],
“comments.date”: [ 2014-09-01, 2014-10-22 ]
}
nested objects 可以用来解决这个问题,每个嵌套对象会被索引为一个隐藏分割文档
{
“comments.name”: [ john, smith ],
“comments.comment”: [ article, great ],
“comments.age”: [ 28 ],
“comments.stars”: [ 4 ],
“comments.date”: [ 2014-09-01 ]
}
{
“comments.name”: [ alice, white ],
“comments.comment”: [ like, more, please, this ],
“comments.age”: [ 31 ],
“comments.stars”: [ 5 ],
“comments.date”: [ 2014-10-22 ]
}
{
“title”: [ eggs, nest ],
“body”: [ making, money, work, your ],
“tags”: [ cash, shares ]
}

设置 nested类型
PUT /my_index
{
“mappings”: {
“blogpost”: {
“properties”: {
“comments”: {
“type”: “nested”,
“properties”: {
“name”: { “type”: “string” },
“comment”: { “type”: “string” },
“age”: { “type”: “short” },
“stars”: { “type”: “short” },
“date”: { “type”: “date” }
}
}
}
}
}
}

然后查询
GET /my_index2/blogpost/_search
{
“query”: {
“nested”: {
“path”: “comments”,
“query”: {
“bool”: {
“must”: [
{
“match”: {
“comments.name”: “White”
}
},
{
“match”: {
“comments.age”: 31
}
}
]
}
}
}
}
}

原创粉丝点击