Home > Net >  Painless script to increase the count if the full path exists or else add the full path and add the
Painless script to increase the count if the full path exists or else add the full path and add the

Time:09-27

I am creating a script to increase the count value of the field if the field full path exist, or else I have to add the full path dynamically. For example, In the below example

  1. If the record already has inner->board1->count, I should increment the value of it by the value of the count
  2. If I don't have inner or board1 or count, I should add them and add the value of the count. Please also note here the inner or board1orcount` are not fixed.

If the value is not an object, I can check using ctx._source.myCounts == null, but I am not sure how to check for the object fields and subfields and sub subfields.

Code

POST test/_update/3
{
  "script": {
        "source": "ctx._source.board_counts = params.myCounts",
    "lang": "painless",
    "params": {
      "myCounts": {
        "inner":{
          "board1":{"count":5},
          "board2":{"count":4},
          "board3":{"temp":1,"temp2":3}
        },
          "outer":{
          "board1":{"count":5},
          "board10":{"temp":1,"temp2":3}
        }
      }
    }
  }
}

CodePudding user response:

I am able to come up with this and working fine.

POST test/_update/3
{
  "script": {
        "source": "{"source": "if (ctx._source['myCounts'] == null) {ctx._source['myCounts'] = [:];} for (mainItem in params.myCounts) { for (accessItemKey in mainItem.keySet()) { if (ctx._source.myCounts[accessItemKey] == null) { ctx._source.myCounts[accessItemKey] = [:];}for (boardItemKey in mainItem[accessItemKey].keySet()) {if (ctx._source.myCounts[accessItemKey][boardItemKey] == null) {ctx._source.myCounts[accessItemKey][boardItemKey] = [:];} for (countItemKey in mainItem[accessItemKey][boardItemKey].keySet()) { if (ctx._source.myCounts[accessItemKey][boardItemKey][countItemKey] == null) { ctx._source.myCounts[accessItemKey][boardItemKey][countItemKey] =mainItem[accessItemKey][boardItemKey][countItemKey]; }else {ctx._source.myCounts[accessItemKey][boardItemKey][countItemKey]  = mainItem[accessItemKey][boardItemKey][countItemKey];}}}}}",
    "lang": "painless",
    "params": {
      "myCounts": {
        "inner":{
          "board1":{"count":5},
          "board2":{"count":4},
          "board3":{"temp":1,"temp2":3}
        },
          "outer":{
          "board1":{"count":5},
          "board10":{"temp":1,"temp2":3}
        }
      }
    }
  }
}
  • Related