elasticsearch 父子文档

父子文档 适用于大量更新的操作

  1. 定义mappings 设置文档父子关系
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    {
    "mappings": {
    "properties": {
    "blog_comments_relation":{
    "type":"join",
    "relations":{
    "blog":"comments"
    }
    },
    "title":{
    "type":"text"
    },
    "content":{
    "type":"keyword"
    }
    }
    }
    }
  2. 索引数据
  • 索引父文档 明确文档id
    script
    1
    2
    3
    4
    5
    6
    7
    8
    PUT /my_blogs/_doc/blog_id_1
    {
    "title":"super book",
    "content":"dfslkfjdsafdskla;klf",
    "blog_contents_relation":{
    "name":"blog"
    }
    }
  • 索引子文当 需指定其父文档id
    script
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    PUT /my_blogs/_doc/comments_id_1?routing=blog_id_1
    {
    "comments":"22222222222",
    "username":"user2",
    "blog_contents_relation":{
    "name":"comments",
    "parent":"blog_id_1"
    }
    }

根据父id查询子文档

1
2
3
4
5
6
7
8
{
"query":{
"parent_id":{
"type":"comments",
"id":"blog_id_1"
}
}
}

根据子文档 查询父文档

1
2
3
4
5
6
7
8
9
10
11
12
{
"query":{
"has_child":{
"type":"comments",
"query": {
"match": {
"username": "user1"
}
}
}
}
}