Elasticsearch 7 新增内部嵌套文档(含JAVA)的操作(High Level REST API)
在实际工作中,我们常把数据整合成嵌套文档,这样方便实现类似sql的关联查询,如何新增关联对象,下面是一个例子:
新API的操作方式一直没找到例子,好不容易试成功的!
原始数据的mapping:
PUT /article_index
{
"mappings" : {
"properties" : {
"author" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"comments" : {
"type": "nested",
"properties" : {
"age" : {
"type" : "long"
},
"comment" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"date" : {
"type" : "long"
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"stars" : {
"type" : "long"
}
}
},
"keyword" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"title" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
新增文档:
PUT /article_index/_doc/1
{
"author": "xxxx",
"title": "Nest coff",
"keyword": "nest kill",
"comments": [
{
"name": "John Smith",
"comment": "Great article",
"age": 28,
"stars": 4,
"date": "2017-09-01"
},
{
"name": "Alice White",
"comment": "More like this please",
"age": 31,
"stars": 5,
"date": "2014-10-22"
}
]
}
新增子文档
POST article_index/_update/1
{
"script" : {
"source": "ctx._source.comments.add(params.new_tag)",
"params" : {
"new_tag" : {
"name": "Big Whitexxx",
"comment": "More like this pleasexx",
"age": 36,
"stars": 5,
"date": "2018-10-22"
}
}
}
}
JAVA代码,真不容易啊!!!!一直没找到案例,按官方文档和上图的kibana操作试了好久
@Test
public void addNested() throws IOException {
UpdateRequest request = new UpdateRequest( "article_index", "2");
Map<String, Object> jsonMap1 = new HashMap<>();
jsonMap1.put("date", new Date());
jsonMap1.put("starts", "1");
jsonMap1.put("name", "cccccc");
jsonMap1.put("comment", "cccccc");
jsonMap1.put("age", "20");
//parameters.put("new", jsonMap1);
Map<String, Object> parameters = Collections.singletonMap("jsonMap1",jsonMap1);Script inline = new Script(ScriptType.INLINE, "painless",
"ctx._source.comments.add(params.jsonMap1)", parameters);
request.script(inline); //comments.add(params.new_tag)
UpdateResponse updateResponse = client.update(
request, RequestOptions.DEFAULT);
}
更多代码请参考:https://github.com/hsn999/Elasticsearch_7_springboot_demo