父连接查询和聚合

参考:elasticsearch6.5父亲文档查询与聚合

join字段的值可以在aggs和 中访问,可以使用parent_id查询查询

GET my_index/_search
{
  \"query\": {
    \"parent_id\": { # 查询父id字段(还请参阅has_parent查询和has_child查询)
      \"type\": \"answer\",
      \"id\": \"1\"
    }
  },
  \"aggs\": {
    \"parents\": {
      \"terms\": {
        \"field\": \"my_join_field#question\", # 在父id字段上聚合(也请参阅子聚合)
        \"size\": 10
      }
    }
  },
  \" _fields\": {
    \"parent\": {
      \" \": {
         \"source\": \"doc[\'my_join_field#question\']\"  # 在 中访问父id \'字段
      }
    }
  }
}

一对多(一个父亲对应多个孩子)

PUT my_index
{
  \"mappings\": {
    \"_doc\": {
      \"properties\": {
        \"my_join_field\": {
          \"type\": \"join\",
          \"relations\": {
            \"question\": [\"answer\", \"comment\"]  
          }
        }
      }
    }
  }
}

question 是answer,comment的父亲。

父连接的多个级别

不建议使用多级关系复制关系模型。每个关系级别都会在查询时增加内存和计算方面的开销。如果您关心性能,则应该对数据进行反规范化。
父母/子女的多重层次:

PUT my_index
{
  \"mappings\": {
    \"_doc\": {
      \"properties\": {
        \"my_join_field\": {
          \"type\": \"join\",
          \"relations\": {
            \"question\": [\"answer\", \"comment\"],  # question is parent of answer and comment
            \"answer\": \"vote\"  # answer is parent of vote
          }
        }
      }
    }
  }
}

上述映射表示如下树:

   question
    /    \\
   /      \\
comment  answer
           |
           |
          vote

为孙子文档建立索引需要一个路由值等于祖父母:

PUT my_index/_doc/3?routing=1&refresh  # 这个子文档必须与它的祖父级和父级位于相同的碎片上
{
  \"text\": \"This is a vote\",
  \"my_join_field\": {
    \"name\": \"vote\",
    \"parent\": \"2\"    # 此文档的父id(必须指向文档)
  }
}
收藏 打印