官网链接:
join datatype | Elasticsearch Guide [6.4] | Elastic
Has Parent Query | Elasticsearch Guide [6.4] | Elastic
es的父子文档和嵌套结构都是处理一对多的关系;父子文档结构的数据都是相同数据结构的存在同一张表中,父子文档路由必须相同;而嵌套结构的子文档必须和父文档是一条数据,查询相对更快但不适合更新操作;
1.建表:
curl -XPUT 'http://127.0.0.1:9200/my_test_join01'
curl -XPUT 'http://127.0.0.1:9200/my_test_join01/_doc/_mapping' -H 'Content-Type:application/json' -d '
{
"_doc":{
"properties":{
"docId":{
"type":"keyword"
},
"companyId":{
"type":"keyword"
},
"robotFlag":{
"type":"integer"
},
"serviceId":{
"type":"keyword"
},
"serviceName":{
"type":"keyword"
},
"createTime":{
"type":"long"
},
"updateTime":{
"type":"long"
},
"questionStatus":{
"type":"integer"
},
"qid":{
"type":"keyword"
},
"qtitle":{
"type":"text",
"fields":{
"keyword":{
"type":"keyword",
"ignore_above":10922
}
}
},
"myRelation":{
"type":"join",
"relations":{
"parentName":"docKnownLearn"
}
}
}
}
}'
2. 插入测试数据
插入父文档:
POST my_test_join01/my_test_join01/f450f67aee0748de8fb96c04d46be127
{
"qid": "f450f67aee0748de8fb96c04d46be127",
"qtitle": "课程卡怎么使用??",
"docId": "111111111111111111111111111111",
"updateServiceName": "我要打十个",
"updateTime": 1628064771,
"serviceId": "e5ba6fc7c42444baa11482fd7274873f",
"questionStatus": 0,
"createServiceName": "我要打十个",
"companyId": "0a53403cb9b34d528bdc11df69c283ff",
"createTime": 1628064771,
"robotFlag": 2,
"myRelation":{
"name":"parentName"
}
}
插入子文档:
POST my_test_join01/my_test_join01/01a0637772e1448c8ca9ad627bf94bd8?routing=f450f67aee0748de8fb96c04d46be127
{
"qtitle": "测试数据qerwvsy5",
"questionFlag": 2,
"docId": "51a1a36278934686945e0da7a49f9649",
"updateTime": 1628082303472,
"questionTypeId": "7eb33948ee92487092800bd29639adda",
"likenessRate": 0.8629167,
"companyId": "0a53403cb9b34d528bdc11df69c283ff",
"createTime": 1628082303472,
"learnId": "01a0637772e1448c8ca9ad627bf94bd8",
"robotFlag": 2,
"learnStatus": 0,
"myRelation": {
"name": "docKnownLearn",
"parent": "f450f67aee0748de8fb96c04d46be127"
}
}
curl -XPOST 'http://127.0.0.1:9200/my_test_join01/_doc/aaaaaaaaaaaaaaaaaaaaaaaaaaa?routing=f450f67aee0748de8fb96c04d46be127' -H 'Content-Type:application/json' -d '{
"qtitle": "测试数据qerwvsy5",
"questionFlag": 2,
"docId": "asdasdasrttt666666666666",
"updateTime": 1628082303472,
"questionTypeId": "7eb33948ee92487092800bd29639adda",
"likenessRate": 0.8629167,
"companyId": "0a53403cb9b34d528bdc11df69c283ff",
"createTime": 1628082303472,
"learnId": "33333333333333333333333333333333",
"robotFlag": 2,
"learnStatus": 0,
"myRelation": {
"name": "docKnownLearn",
"parent": "f450f67aee0748de8fb96c04d46be127"
}
}'
3. 根据父文档查询,返回符合条件的子文档数据
curl -XGET "127.0.0.1:9200/my_test_join01/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size":0,
"query":{
"has_parent":{
"query":{
"query_string":{
"query":"qtitle.keyword:*使用*"
}
},
"parent_type":"parentName"
}
},
"aggregations":{
"mainAgg":{
"terms":{
"field":"docId",
"order":[
{
"_count":"desc"
},
{
"_key":"asc"
}
]
}
}
}
}'