定义某个索引中关于嵌套部分的mapping如下:
"custLabels": {
"type": "nested",
"properties": {
"action": {
"type": "keyword"
},
"labelName": {
"type": "keyword"
},
"labelValue": {
"type": "keyword"
}
}
},
@Field(type= FieldType.Nested)
private List<ElaCustLabel> custLabels;
1. 嵌套查询 每个返回结果中custLabels 同时满足这三个条件:
POST /test_summary/_search
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "custLabels",
"query": {
"bool": {
"must": [
{
"match": {
"custLabels.labelValue": "0025"
}
}
]
}
}
}
},
{
"nested": {
"path": "custLabels",
"query": {
"bool": {
"must": [
{
"match": {
"custLabels.labelValue": "0030"
}
}
]
}
}
}
},
{
"nested": {
"path": "custLabels",
"query": {
"bool": {
"must": [
{
"match": {
"custLabels.labelValue": "0002"
}
}
]
}
}
}
}
]
}
}
}
2. 修改指定索引中某个文档的嵌套数据--新增一个数据项
POST /test_summary/_doc/Rhm6hYEBNXXwNUBZ_ZwM/_update
{
"script": {
"source": """if(ctx._source.containsKey('custLabels')){
def targets = ctx._source.custLabels.findAll(custLabel -> custLabel.labelValue == params.custLabels.labelValue);if(targets.size() == 0) {ctx._source.custLabels.add(params.custLabels)\n\n}\n\n}else{\n\nctx._source.custLabels=[params.custLabels];}""",
"lang": "painless",
"params": {
"custLabels": {
"labelValue": "0024",
"labelName": "老年"
}
}
}
}
3.修改指定索引中某个文档的嵌套数据--根据操作类型新增或者删除
POST /test_summary/_doc/Rhm6hYEBNXXwNUBZ_ZwM/_update
{
"script": {
"source": """
for(int i=0;i<ctx._source.custLabels.length;i++){
for(int j= 0; j<params.custLabels.length; j++ ){
if(ctx._source.custLabels[i].labelValue == params.custLabels[j].labelValue && params.custLabels[j].action == 'DELETE'){
ctx._source.custLabels.remove(i);
break;
}
}
}
for(int n= 0; n<params.custLabels.length; n++ ){
int addFlag = 1;
for(int k=0;k<ctx._source.custLabels.length;k++){
if(ctx._source.custLabels[k].labelValue == params.custLabels[n].labelValue && params.custLabels[n].action == 'ADD'){
addFlag = 0;
break;
}
}
if(addFlag == 1 && params.custLabels[n].action == 'ADD'){
ctx._source.custLabels.add(params.custLabels[n]);
}
}
""",
"lang": "painless",
"params": {
"custLabels": [{"labelValue":"0001","labelName":"已用信","action":"DELETE"},
{"labelValue":"0024","labelName":"老年","action":"ADD"},
{"labelValue":"0029","labelName":"贷款","action":"ADD"}
]
}
}
}