天天看點

elasticsearch進行parent/child類型聚合的測試

elasticsearch進行parent/child類型聚合的測試:

1、查詢父類型可以inner_hits得到子類型資料,反之也行

{
  "query": {
    "has_child": {
      "query": {
        "match": {
          "lid": "00000"
        }
      },
      "child_type": "article",
      "inner_hits": {}
    }
  }
}
           
{
  "query": {
    "has_parent": {
      "query": {
        "match": {
          "content": "公司"
        }
      },
      "parent_type": "main",
      "inner_hits": {}
    }
  }
}
           

2、has_parent、has_child查詢的時候,has_parent是通過查詢父類型得到子類型的清單結果,has_child反之。

3、has_parent是通過查詢父類型得到子類型的清單結果,這時同時對父類型某字段進行聚合,無聚合結果傳回。has_child查詢的時候對子類型某字段進行聚合也沒有結果。

{
  "query": {
    "has_child": {
      "query": {
        "match": {
          "lid": "00000"
        },
        "aggs": {
          "group_by_mid": {//查詢結果中沒有聚合資料group_by_mid
            "terms": {
            "field": "mid"
           }
        }
       }
      },
      "child_type": "article",
      "inner_hits": {}
    }
  }
}
           

4、has_parent是通過查詢父類型得到子類型的清單結果,這時同時對子類型某字段進行聚合,得到聚合結果,但是傳回的查詢清單也為子類型,雖然inner_hits可以得到對應父類型結果,但是如果父子是一對多關系,可能得到的單分頁父類型資料有重複。

{
  "query": {
    "has_child": {
      "query": {
        "match": {
          "lid": "00000"
        }
      },
      "child_type": "article",
      "inner_hits": {}
    }
  },
  "aggs": {
    "group_by_years": {//有聚合資料group_by_years傳回
      "terms": {
        "field": "years"
      }
    }
  }
}
           

5、是以,如果查詢父類型,并且結果分頁清單要顯示父類型資料,同時還要取得相關子類型資料的聚合結果的話。隻有查詢兩次實作:

1)對父類型進行普通的查詢,并取得查詢分頁清單結果。

2)使用has_parent,用同樣的條件對父類型查詢,傳回子類型資料分頁清單結果,同時對子類型某字段進行聚合,擷取該字段的聚合資料。

繼續閱讀