嵌套文档
父子文档
7.5 官方文档
父子文档,只是使用一个 join 类型属性来描述,并在参数 relations 中定义父子关系。
使用父子文档,一定要留意索引的主分片数,当只有一个主分片,后续的路由参数空缺也没问题,但多于两个主分片,就不行了。
定义Mapping
PUT my-index-000001{"mappings": {"properties": {"my_id": {"type": "keyword"},"my_join_field": {// 重点"type": "join","relations": {"question": "answer"}}}}}
my_join_field父子关系字段名,自定义,一个文档最多只有一个- 类型为
join,标志父子文档relations父子文档结构,可有多个
索引父文档
索引副文档时两种方式等价
PUT my-index-000001/_doc/1?refresh{"my_id": "1","text": "This is a question","my_join_field": {"name": "question"}}PUT my-index-000001/_doc/1?refresh{"my_id": "1","text": "This is a question","my_join_field": "question"}
索引子文档
PUT my-index-000001/_doc/3?routing=1&refresh{"my_id": "3","text": "This is an answer","my_join_field": {"name": "answer","parent": "1"}}
- 强制指定路由值,就是父文档id,确保父文档、子文档都在同一个分片上
- 在_source 中描述
join类型字段的子文档名称- 同上,指定关联父文档id
搜索子文档
通过子文档id查询,需要指定路由
a1子文档idq1路由 ->父文档id
GET '120.78.207.190:9200/my-index-000001/_doc/a1?routing=q1'
通过父文档id查询所有关联的子文档
GET my-index-000001/_search{"query": {"parent_id": {"type": "answer","id":1}}}
父文档条件 has_parent 查询
GET my-index-000001/_search{"query": {"has_parent": {"parent_type": "question","query": {"match" : {"my_id": "q1"}}}}}
搜索父文档
子条件 has_child 查询
GET my-index-000001/_search{"query": {"has_child": {"type": "answer","query": {"match" : {"my_id": "a1"}}}}}
