ElasticSearch7.0 关联查询之父子文档
ES7中取消了type这一层级(相当于关系数据库中的table,mongo中的collection),所有文档平铺存放在同一个index中,对于一对多的关联关系,ES7中有两种方式:
父子文档,所有文档都是平级的,通过特殊的字段类型join来表示层级关系
嵌套文档,类似于json中的嵌套数组,需要申明字段类型为nested
本篇针对父子文档这一类型
官方文档地址:https://www.elastic.co/guide/en/elasticsearch/reference/current/parent-join.html
本项目地址:
https://gitee.com/xiiiao/es-learning.git
创建index
PUT my-index-join_family
{
"mappings":{
"properties":{
"my_id":{
"type":"keyword"
},
"name":{
"type":"keyword"
},
"level":{
"type":"keyword"
},
"join_filed":{ //1关联的字段名,可以随意取
"type":"join", //类型需要定义为join
"relations":{ //定义层级关系,grand_parent ->parent -> child
"grand_parent":"parent",
"parent":"child"
}
}
}
}
}
以上创建了一个祖->父->子的关联关系,一个父可以有多个子,多个子用数组的方式申明
插入顶层父节点
Rest API
PUT my-index-join_family/_doc/1?refresh
{
"my_id": "1",
"name": "grandPa",
"join_filed": { //表名这个文档属于grand_parent这一层级
"name": "grand_parent"
}
}
RestHighLevelClient实现
public void addGrandPa( String name) {
String id = UUID.randomUUID().toString();
JoinFamily member = new JoinFamily();
member.setName(name);
member.setLevel("1");
member.setMy_id(id);
JoinField joinField = new JoinField();
joinField.setName("grand_parent");
member.setJoin_filed(joinField);
String source = JSON.toJSONString(member);
log.info("source: " + source);
IndexRequest indexRequest = new IndexRequest("my-index-join_family").id(id).source(source, XContentType.JSON)
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
try {
IndexResponse out = client.index(indexRequest, RequestOptions.DEFAULT);
log.info(out.getId());
} catch (IOException e) {
log.error("", e);
}
}
插入父节点
PUT my-index-join_family/_doc/2?routing=1&refresh
{
"my_id": "2",
"name": "parent",
"join_filed": { //表名这个文档属于parent这一层级
"name": "parent" ,
"parent":"1&#