Foreach index action error

Here is my watch to index and filter multiple docs in one execution.

PUT foo/_doc/1
{
  "name" : {
    "first" : "Kobe",
    "last" : "Bryant"
  },
  "bar":"TO REMOVE"
}
PUT foo/_doc/2
{
  "name" : {
    "first" : "Stephen",
    "last" : "Curry"
  },
  "bar":"TO REMOVE"
}

PUT foo/_doc/3
{
  "name" : {
    "first" : "Dirk",
    "last" : "Nowitzki"
  },
  "bar":"TO REMOVE"
}

  POST _watcher/watch/_execute
{
  "watch" : {
  "trigger": {
    "schedule": {
      "interval": "2s"
    }
  },
  "input": {
    "search": {
      "request": {
        "search_type": "query_then_fetch",
        "indices": [
          "foo"
        ],
        "rest_total_hits_as_int": true,
        "body": {
          "query": {
            "match_all": {}
          }
        }
      }
    }
  },
  "condition": {
    "compare": {
      "ctx.payload.hits.total": {
        "gt": 0
      }
    }
  },
  "actions": {
      "index_payload": {
        "transform" : {
          "script" : 
          """
          def docs = [];
          for(item in ctx.payload.hits.hits) { 
                def d = item._source.clone(); 
 		d['end_timestamp'] = d['@timestamp']; 
 		d['@timestamp'] = ctx['trigger']['triggered_time'];
 		d.remove('bar');
 		docs.add(d);
          } 
                return [ '_doc' : docs];
          """
        },
        "index": {
          "index": "reindex-test",
          "doc_type": "_doc"
        }
      }
    }
  }
}

To remove use d.remove and the name field.

Everything is in the watch here provided with examples. Thanks @spinscale & @hardbap

You may want to add this as an example since it's really hard to understand ( for me at-least ) and this is a very useful.

1 Like