版本
spring-boot-starter-data-elasticsearch: 2.1.3 RELEASE
es服务版本:elasticsearch-6.7.0
步骤
1、 测试表名
sys_object
2、 先在服务器建立父子表结构
{
"mappings": {
"_doc": {
"properties": {
"type": {
"type": "join",
"relations": {
"parent": "child"
}
}
}
}
}
}
查看表结构应该是这样的。
3、 建立父实体
@Data
@Document(indexName = "sys_object", type="_doc")
public class SysObjectModel {
@Id
@GeneratedValue
private String id;
private String projectId;
@Field(type = FieldType.Auto)
private JSONObject type;
}
public interface ISysObjectEsService extends org.springframework.data.repository.Repository<SysObjectModel, String>, CrudRepository<SysObjectModel, String> {
}
4、 建立子实体
@Data
@Document(indexName = "sys_object", type="_doc")
public class SysObject3DChildModel {
@Id
@GeneratedValue
private String id;
@Field(type = FieldType.Auto)
private JSONObject type;
private String objectId;
private String docId;
private String nodeId;
private String projectId;
}
public interface ISysObject3DChildEsService extends org.springframework.data.repository.Repository<SysObject3DChildModel, String>, CrudRepository<SysObject3DChildModel, String> {
}
这里父子索引名称相同 因为是同一张表。
5、保存数据测试
注意这里的type的值设置
5.1 保存父
String parentId = UUID.randomUUID().toString();
SysObjectModel sysObjectModel = new SysObjectModel();
JSONObject parentType = new JSONObject();
parentType.put("name", "parent");
sysObjectModel.setType(parentType);
sysObjectModel.setId(parentId);
sysObjectEsService.save(sysObjectModel);
5.2 保存子
SysObject3DChildModel sysObject3DChildModel = new SysObject3DChildModel();
sysObject3DChildModel.setObjectId(parentId);
sysObject3DChildModel.setId(UUID.randomUUID().toString());
JSONObject childType = new JSONObject();
childType.put("name", "child");
childType.put("parent", parentId);
sysObject3DChildModel.setType(childType);
sysObject3DChildModel.setObjectId(parentId);
sysObject3DChildService.save(sysObject3DChildModel);
其中子的service的save逻辑是
public void save(SysObject3DChildModel sysObject3DChildModel) {
String objectId = sysObject3DChildModel.getObjectId();
Request request = new Request("PUT",
String.format("/sys_object/_doc/%s?routing=%s&refresh",
sysObject3DChildModel.getId(), objectId));
String putSql = JSON.toJSONString(sysObject3DChildModel);
HttpEntity entity = new NStringEntity(putSql, ContentType.APPLICATION_JSON);
request.setEntity(entity);
try {
this.client.performRequest(request);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
可参考官方文档
6 一条父子数据内容
父
子
通过父ID查询子