You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Logstash Ruby Filter解析JSON并将键值插入对应JSON块的方法

Got it, let's fix this Logstash Ruby filter for you. Here's the corrected code along with explanations to make sure it does exactly what you need:

Solution Code
filter {
  ruby {
    code => '
      # Iterate over all top-level key-value pairs in the event
      event.to_hash.each do |ip, details|
        # Skip Logstash built-in fields to avoid unintended processing
        next if ["@timestamp", "@version"].include?(ip)
        
        # Add the "host" field to the child object, using the IP as its value
        details["host"] = ip
        
        # Optional: Uncomment below to split each IP's data into a separate Logstash event
        # event.spawn(details)
      end
    '
  }
}
How It Works

Let's break down what each part does:

  • Iterate over top-level keys: event.to_hash.each do |ip, details| grabs every key-value pair in your input. The ip variable holds your top-level IP address, and details is the child object associated with it.
  • Skip built-in fields: We skip Logstash's auto-added fields like @timestamp and @version so we don't accidentally treat them as IP addresses. You can add more fields to this list if your input has other non-IP top-level keys.
  • Add the host field: details["host"] = ip directly injects the IP address into the child object as the host field—exactly what you asked for.
  • Optional: Split into separate events: If you want each IP's data to become its own independent Logstash event (super useful for indexing into Elasticsearch or other destinations), uncomment the event.spawn(details) line. This will create a new event for every IP, with a flat structure that includes the host field.
Example Input/Output

Sample Input

{
  "192.168.1.1": {"status": "up", "response_time": 0.2},
  "10.0.0.5": {"status": "down", "response_time": null}
}

Output (Keeping Original Top-Level Structure)

{
  "192.168.1.1": {"status": "up", "response_time": 0.2, "host": "192.168.1.1"},
  "10.0.0.5": {"status": "down", "response_time": null, "host": "10.0.0.5"},
  "@timestamp": "2024-05-20T14:22:00.123Z",
  "@version": "1"
}

Output (With Split Events)

Each IP becomes a standalone event:

{"status": "up", "response_time": 0.2, "host": "192.168.1.1", "@timestamp": "...", "@version": "1"}
{"status": "down", "response_time": null, "host": "10.0.0.5", "@timestamp": "...", "@version": "1"}

内容的提问来源于stack exchange,提问作者Darshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:23:42