Logstash 5.0 Ruby Filter无法更新数组中的哈希值

时间:2017-06-23 13:46:29

标签: ruby filter logstash

我是Logstash和Ruby的新手,今天我遇到了一个微妙的问题。

我的输入JSON如下:

{
  "1": "1",
  "2": "2",
  "market": [
    {
      "id": "1",
      "name": "m1"
    },
    {
      "id": "2",
      "name": "m2"
    }
  ]
}

我的过滤器类似于以下代码,我想将事件[“1”]设置为m1,事件[“2”]设置为m2,事件[“market”] [0] [“id”]设置为m1 ,event [“market”] [1] [“id”]到m2:

filter {
    ......
    ruby {
        code => "
        markets = event.get('market')
        markets.each_index do |index| 
            event.set(markets[index]['id'], markets[index]['name']) 
            markets[index]['id'] = markets[index]['name']
        end
    "
    }
    ......
}

输出如下:

{
  "1": "m1",
  "2": "m2",
  "market": [
    {
      "id": "1",
      "name": "m1"
    },
    {
      "id": "2",
      "name": "m2"
    }
  ]
}

事件[“1”]和事件[“2”]获得预期值,但事件[“市场”] [0] [“id”]和事件[“市场”] [1] [“ id“]不,我想知道为什么?所需的输出应为:

{
  "1": "m1",
  "2": "m2",
  "market": [
    {
      "id": "m1",
      "name": "m1"
    },
    {
      "id": "m2",
      "name": "m2"
    }
  ]
}

PS:我正在使用的logstash是版本5.0。

1 个答案:

答案 0 :(得分:0)

我认为这是因为Logstash 5.0中引入了新的Event API。将我的过滤器更改为以下内容后,我得到了所需的输出:

filter {
    ......
    ruby {
        code => "
        markets = event.get('market')
        markets.each_index do |index| 
           event.set(markets[index]['id'], markets[index]['name']) 
           markets[index]['id'] = markets[index]['name']
        end
        event.set('market', markets) // comment: adding this setter in the filter
    "
    }
    ......
}

根据Logstash Git Issue,"在事件中设置后对集合进行变异具有未定义的行为"。