在Elasticsearch中,`Parent Aggregation`是一種特殊的單桶聚合,用于選擇具有指定類型的父文檔,這些類型是通過一個`join`字段定義的。以下是關于`Parent Aggregation`的詳細介紹:
1.基本概念
`Parent Aggregation`是一種聚合操作,主要用于處理父-子關系的文檔。通過這種聚合,可以將子文檔的聚合結果映射到父文檔上,從而實現跨文檔類型的聚合。
2.應用場景
假設有一個索引,其中包含問題(`question`)和答案(`answer`)兩種類型的文檔。`answer`文檔通過`join`字段與`question`文檔關聯。通過`Parent Aggregation`,可以將答案的聚合結果(如答案的數量、答案的作者等)映射到問題文檔上。
3.配置方法
在使用`Parent Aggregation`時,需要指定以下內容:
? `type`:指定子文檔的類型。例如,在問題和答案的場景中,`type`應設置為`answer`。
? 子聚合:可以在`Parent Aggregation`中嵌套其他聚合操作,例如`terms`、`avg`等。
4.示例
以下是一個具體的例子,展示如何使用`Parent Aggregation`將答案的作者聚合到問題的標簽上:
索引映射
```json
PUT parent_example
{
? "mappings": {
? ? "properties": {
? ? ? "join": {
? ? ? ? "type": "join",
? ? ? ? "relations": {
? ? ? ? ? "question": "answer"
? ? ? ? }
? ? ? }
? ? }
? }
}
```
索引文檔
```json
PUT parent_example/_doc/1
{
? "join": {
? ? "name": "question"
? },
? "body": "I have Windows 2003 server and i bought a new Windows 2008 server...",
? "title": "Whats the best way to file transfer my site from server to a newer one?",
? "tags": [
? ? "windows-server-2003",
? ? "windows-server-2008",
? ? "file-transfer"
? ]
}
?
PUT parent_example/_doc/2?routing=1
{
? "join": {
? ? "name": "answer",
? ? "parent": "1"
? },
? "owner": {
? ? "location": "Norfolk, United Kingdom",
? ? "display_name": "Sam",
? ? "id": 48
? },
? "body": "Unfortunately you're pretty much limited to FTP...",
? "creation_date": "2009-05-04T13:45:37.030"
}
```
查詢
```json
POST parent_example/_search?size=0
{
? "aggs": {
? ? "top-names": {
? ? ? "terms": {
? ? ? ? "field": "owner.display_name.keyword",
? ? ? ? "size": 10
? ? ? },
? ? ? "aggs": {
? ? ? ? "to-questions": {
? ? ? ? ? "parent": {
? ? ? ? ? ? "type": "answer"
? ? ? ? ? },
? ? ? ? ? "aggs": {
? ? ? ? ? ? "top-tags": {
? ? ? ? ? ? ? "terms": {
? ? ? ? ? ? ? ? "field": "tags.keyword",
? ? ? ? ? ? ? ? "size": 10
? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? }
? ? ? }
? ? }
? }
}
```
響應
```json
{
? "aggregations": {
? ? "top-names": {
? ? ? "buckets": [
? ? ? ? {
? ? ? ? ? "key": "Sam",
? ? ? ? ? "doc_count": 1,
? ? ? ? ? "to-questions": {
? ? ? ? ? ? "doc_count": 1,
? ? ? ? ? ? "top-tags": {
? ? ? ? ? ? ? "buckets": [
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? "key": "file-transfer",
? ? ? ? ? ? ? ? ? "doc_count": 1
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? "key": "windows-server-2003",
? ? ? ? ? ? ? ? ? "doc_count": 1
? ? ? ? ? ? ? ? },
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? "key": "windows-server-2008",
? ? ? ? ? ? ? ? ? "doc_count": 1
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ]
? ? ? ? ? ? }
? ? ? ? ? }
? ? ? ? }
? ? ? ]
? ? }
? }
}
```
5.注意事項
? `Parent Aggregation`依賴于`join`字段來定義父-子關系。
? 子聚合可以是任意類型的聚合操作,但必須與父文檔的類型兼容。
通過`Parent Aggregation`,可以有效地將子文檔的聚合結果映射到父文檔上,從而實現復雜的跨文檔類型的聚合操作。