Elasticsearch中nested的使用

nested

  • 场景描述:

    在存储文档时,一个文档的属性包含多个对象时,需要使用nested类型进行定义。

  • 场景例子:

    一个文档的 Tags 属性,Tags可以包含多个Tag,每个Tag都有TagKeyTagValue属性。

    "Tags": {
    	"Tag": [
    		{
    			"TagValue": "production",
    			"TagKey": "env"
    		},
    		{
    			"TagValue": "xxxx",
    			"TagKey": "group"
    		}
    	]
    },
    

    如果以Tags属性以普通的object类型进行存储时,ES中没有内部对象的概念,会将内部对进行扁平化,扁平化后结如下:

    {
        TagValue:[production,knorrcnyh5],
        TagKey:[env,group]
    }
    

    扁平化处理过后,就无法再获得envproduction的关系了。在你查询env等于production的所有文档时,不符合条件的文档也会出现。

  • 解决办法:

    使用nested进行存储,mapping的定义如下:

    project:
        properties:
            tags:
              type: nested
              properties: 
                TagKey: 
                  type: keyword
                TagValue:
                  type: keyword
            domain:
              type: text
    

    nested进行增删改查:

    • 查询 body:
    {
            query:{
                nested:{
                    path: 'tags',
                    query:{
                        bool:{
                            must:[
                                {match:{'tags.TagKey':'xxx'}},
                                {match:{'tags.TagValue':yyy}}
                            ]
                        }
                    }
                }
            }
        }
    
    • 增加 body:
    bulk.push({
        index: {
            _index: 'project',
            _type: 'asset',
            _id: instance.InstanceId,
            parent: parentId,
        },
    });
    bulk.push({
        tags: getTags(instance), 
    }); 
    
    const getTags = ( instance ) => {
    const tags = [];
    for(let i = 0 ;i < instance.Tags.Tag.length; i++) {
        tags.push (
            { TagKey: instance.Tags.Tag[i].TagKey, TagValue: instance.Tags.Tag[i].TagValue}
        )
    }
    return tags;
    }
    
    • 修改 body :
    {
         "script": {
            "source": "for(e in ctx._source.tags){if (e.tagKey == 'env') {e.tagValue = 'xxx';}}" 
          }
    }
    
    • 删除 body :
    {
        "script": {
            "lang": "painless",
            "source": "ctx._source.tags.removeIf(it -> it.tagKey == 'xxx');"
        }
    }
    
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值