主要內容:nested 類型查詢以及聚合操作
1、nested object
冗余數據方式的來建模,其實用的就是object類型,我們這里又要引入一種新的object類型,nested object類型
修改mapping,將comments的類型從object設置為nested
PUT /blogs
{
"mappings": {
"properties": {
"comments": {
"type": "nested",
"properties": {
"name": {
"type": "keyword"
},
"comment": {
"type": "keyword"
},
"age": {
"type": "short"
},
"stars": {
"type": "short"
},
"date": {
"type": "date"
}
}
}
}
}
}
插入數據:
PUT blogs/_doc/6
{
"title": "花無缺發表的一篇帖子",
"content": "我是花無缺,大家要不要考慮一下投資房產和買股票的事情啊。。。",
"tags": [ "投資", "理財" ],
"comments": [
{
"name": "小魚兒",
"comment": "什么股票啊?推薦一下唄",
"age": 28,
"stars": 4,
"date": "2016-09-01"
},
{
"name": "黃藥師",
"comment": "我喜歡投資房產,風,險大收益也大",
"age": 31,
"stars": 5,
"date": "2016-10-22"
}
]
}
針對nested類型進行搜索
GET blogs/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "花無缺"
}
},
{
"nested": {
"path": "comments",
"score_mode": "avg", ## max,min,avg,none,默認是avg
"query": {
"bool": {
"must": [
{
"match": {
"comments.name": "黃藥師"
}
},
{
"match": {
"comments.age": 31
}
}
]
}
}
}
}
]
}
}
}
score_mode:如果搜索命中了多個nested document,如何將多個nested document的分數合并為一個分數
2、針對nested 類型進行數據分析
我們講解一下基于nested object中的數據進行聚合分析
聚合數據分析的需求1:按照評論日期進行bucket劃分,然后拿到每個月的評論的評分的平均值
GET /blogs/_search
{
"size": 0,
"aggs": {
"comments_path": {
"nested": {
"path": "comments"
},
"aggs": {
"group_by_comments_date": {
"date_histogram": {
"field": "comments.date",
"calendar_interval": "month",
"format": "yyyy-MM"
},
"aggs": {
"avg_stars": {
"avg": {
"field": "comments.stars"
}
}
}
}
}
}
}
}
GET /blogs/_search
{
"size": 0,
"aggs": {
"comments_path": {
"nested": {
"path": "comments"
},
"aggs": {
"group_by_comments_age": {
"histogram": {
"field": "comments.age",
"interval": 10
},
"aggs": {
"reverse_path": {
"reverse_nested": {}, ## 根據外層的tag進行劃分
"aggs": {
"group_by_tags": {
"terms": {
"field": "tags.keyword"
}
}
}
}
}
}
}
}
}
}