#第一步 在mapping中创建映射关系,
#映射字段名称为my-join-field
#类型为join
#映射关系为:
#父类型:parent
#子类型:child
PUT /my-index
{
"mappings": {
"properties": {
"my-join-field": {
"type": "join",
"relations": {
"parent": "child"
}
}
}
}
}
#添加父文档1
#指定文档类型"my-join-field":"parent"
PUT /my-index/_doc/parentId1?refresh
{
"id":"parentId1",
"name":"parent1",
"my-join-field":"parent"
}
#添加父文档2
#指定文档类型"my-join-field":"parent"
PUT /my-index/_doc/parentId2?refresh
{
"id":"parentId2",
"name":"parent2",
"my-join-field":"parent"
}
#添加子文档1
#指定文档类型和所属父id
#指定routing,父子文档必须在同一分片
PUT /my-index/_doc/childId1?routing=1&refresh
{
"id":"childId1",
"name":"child1",
"my-join-field":{
"name":"child",
"parent": "parentId1"
}
}
#添加子文档2
#指定文档类型和所属父id
PUT /my-index/_doc/childId2?routing=1&refresh
{
"id":"childId2",
"name":"child2",
"my-join-field":{
"name":"child",
"parent": "parentId2"
}
}
#添加子文档3
#指定文档类型和所属父id
PUT /my-index/_doc/childId3?routing=1&refresh
{
"id":"childId3",
"name":"child3",
"my-join-field":{
"name":"child",
"parent": "parentId1"
}
}
#查找child1的parent
GET /my-index/_search
{
"query": {
"has_child": {
"type": "child",
"query": {
"term": {
"name": {
"value": "child1"
}
}
}
}
}
}
#查找child1以及child1的parent
GET /my-index/_search
{
"query": {
"bool": {
"filter": [
{
"bool": {
"should": [
{
"has_child": {
"type": "child",
"query": {
"term": {
"name": {
"value": "child1"
}
}
},
"inner_hits": {
}
}
}
]
}
}
]
}
}
}
#查找parent1的child
GET /my-index/_search
{
"query": {
"has_parent": {
"parent_type": "parent",
"query": {
"term": {
"name": {
"value": "parent1"
}
}
}
}
}
}
#根据parentId查找child
GET /my-index/_search
{
"query": {
"parent_id": {
"type": "child",
"id": "parentId1"
}
}
}