官方文档:
https://www.elastic.co/guide/en/elasticsearch/reference/current/parent-join.html
1、完整文档
{
"mappings": {
"_doc": {
"properties": {
"event_join_user": {
"type": "join",
"relations": {
"user": "event"
}
},
"user":{
"properties": {
"id":{
"type":"long"
},
"user_name":{
"type":"keyword"
}
}
},
"event":{
"properties": {
"id":{
"type":"long"
},
"user_id":{
"type":"long"
},
"app_version":{
"type":"keyword"
}
}
}
}
}
}
}
2、join关系
event_join_user 为join名称,可以随意取。
6.X版本以上,type只能设置为join
relations表达文档关系,前为父,后为子,即user为父文档,event为子文档
"event_join_user": {
"type": "join",
"relations": {
"user": "event"
}
}
3、设定父子文档各自的字段描述要求
这,没什么可说的。
4、提交父文档
//_id=1
PUT http://ip:port/user_event/_doc/1?refresh
{
"id": 1,
"user_name": "user1",
"event_join_user": "user"
}
//_id=2
PUT http://ip:port/user_event/_doc/2?refresh
{
"id": 2,
"user_name": "user2",
"event_join_user": "user"
}
5、提交子文档
关键点:
a、参数routing为父文档_id
b、event_join_user父子关联关系,指定name为子文档名(event),指定父文档id(parent)
//_id=4
http://ip:port/user_event/_doc/4?routing=1&refresh
{
"id": 4,
"user_id":1,
"app_version": "2.2.10",
"event_join_user": {
"name": "event",
"parent": "1"
}
}
6、根据父文档条件查询子文档
查询父文档user_name=user1的所有子文档
{
"query": {
"has_parent" : {
"parent_type" : "user",
"query" : {
"match" : {
"user_name" : "user1"
}
}
}
}
}
7、根据子文档条件查询父文档
查询子文档中app_version=2.2.10所有文档的父文档
{
"query":{
"has_child":{
"type":"event",
"query":{
"match":{
"app_version":"2.2.10"
}
}
}
}
}
父id=1的所有子文档
{
"query": {
"parent_id": {
"type": "event",
"id": "1"
}
}
}
8、父条件、子字段条件联合
{
"query": {
"bool": {
"must": [
{
"terms": {
"vipLevel": ["1","2"]
}
},
{
"has_child": {
"type": "event",
"query": {
"range": {
"startTime": {"gt":"2019-11-03 00:00:00","lt":"2029-01-01 00:00:00","format":"yyyy-MM-dd HH:mm:ss"}
}
}
}
}
]
}
}
}