Script to create field if it does not already exist


#1

I have created a script that records the history of any updates to a document. It simply copies the current object to a history object. That part is working fine.

The problem I have is that the tag names need to be dynamic and so when I run the same script for a new tag name, it cannot move the current values to the history field as it does not exist.

How can I check if a field exists using a script and then create it if it does not exist?

The structure of the documents is below:

tags:{
"hot":{
"currentValues":{
"dateTime": 123123124,
"taggedBy": user
},
"tagHistory":{
"dateTime": 123123124,
"taggedBy": user
},
"dateTime": 1223423124,
"taggedBy": user2

}}}}}

Thanks!


(Ryan Ernst) #2

Can you give an example of the current script you are using?


#3

So, having rethought the structure of this index, what I want to achieve is the following:

tags:[
   {hot:
    {current:{tagDate:1231231233, taggedbyUser: user1, tagStatus: true},
    history:[ {tagDate:123444433, taggedbyUser: user1, tagStatus: true},
         {tagDate:1234412433, taggedbyUser: user1, tagStatus: true}
   ]
 }

  {interesting:
     {current:{tagDate:1231231233, taggedbyUser: user1, tagStatus: true},
     history:[ {tagDate:123444433, taggedbyUser: user1, tagStatus: true},
           {tagDate:1234412433, taggedbyUser: user1, tagStatus: true}
     ]
} 
]

The tag names in this example are "hot" and "interesting", however the user will be able enter any tag name they want, so these are in no way predefined. When a user tags a document in elastic and the tag that is applied already exists in elastic, it should more the "current" tag to the "history" array and then overwrite the "current" tag with the new values.

I also posted this to stack overflow and so far the closes thing that I have to a working script is:

int num = -1;
for (int i = 0; i < ctx._source.tags.size(); i++) {
    if (ctx._source.tags.get(i).get(param2) != null) {
        num = i;
        break;
    };
};
if (num == -1) {
    return;
};
if (ctx._source.tags.get(num).get(param2).history == null)
    ctx._source.tags.get(num).get(param2).history = new ArrayList();
ctx._source.tags.get(num).get(param2).history.add(ctx._source.tags.get(num).get(param2).current);
ctx._source.tags.get(num).get(param2).current = param1;

However, this is not working for me.


(system) #4

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.