Update numeric and float fields in elasticsearch client

413 Views Asked by At

I am bit new to elasticsearch client. I have not done any type of predefined mapping to any field, because I might add some new field to the documents in future. My data looks like this:-

{
    "segmentId": "4700-b70e-881",
    "segmentName": "test",
    "data": "This is a test data",
    "dataId": "70897e86-9d69-4700-b70e-881a7f74e9f9",
    "augmented": false,
    "createdBy": {
        "email": "[email protected]",
        "primaryKey": "902d2b57-54e6",
        "secondaryKey": "adcc-f20423822c93"
    },
    "status": "active",
    "createdAt": 1617422043554,
    "updatedAt": 1617422043554
}

I wanted to update 3 fields by using updateByQuery. I was trying below approach.

await esClient.updateByQuery({
    index: "data",
    type: "doc",
    refresh: true,
    body:{
        query:{
            match: {
                dataId: "70897e86-9d69-4700-b70e-881a7f74e9f9"
            }
        },
        script:{
            lang:"painless",
            source:`ctx._source.data='This is updated test data';ctx._source.updatedAt=${Date.now()};ctx._source.segmentId=null`
        }
    }
})

I am getting compilation error because of updatedAt and segmentId, When I pass as string it works, like:-

source:`ctx._source.data='This is updated test data';ctx._source.updatedAt='${Date.now()}';ctx._source.segmentId='null'`
1

There are 1 best solutions below

0
On

I found a way to solve the above issue,

await esClient.updateByQuery({
    index: "data",
    type: "doc",
    refresh: true,
    body:{
        query:{
            match: {
                dataId: "70897e86-9d69-4700-b70e-881a7f74e9f9"
            }
        },
        script:{
            lang:"painless",
            source:`ctx._source.data='This is updated test data';ctx._source.updatedAt=params.date;ctx._source.segmentId=params.segmentId`,
            params:{
                date: Date.now(),
                segmentId: null
            }
        }
    }
});