首页 > 解决方案 > 使用 if-else 和 Logstash 拆分

问题描述

我有一个名为descriptiondelimited with的字符串字段_

我将其拆分如下:

filter {
    mutate {
        split => ["description", "_"]
        add_field => {"location" => "%{[description][3]}"}
    }

如何检查拆分值是否为空?

我尝试过:

if !["%{[description][3]}"] {
    # do something
}

if ![[description][3]] {
    # do something
}

if ![description][3] {
    # do something
}

它们都不起作用。

目标是将新字段的值location作为其实际值或通用值,例如NA.

标签: logstash

解决方案


你犯了一个非常简单的错误mutate split

这个

mutate {
        split => ["description", "_"]
        add_field => {"location" => "%{[description][3]}"}
    }

本来应该

mutate {
        split => ["description"=> "_"]   <=== see I removed the comma and added =>
        add_field => {"location" => "%{[description][3]}"}
    }

这是我测试过的样本

filter {
  mutate {
        remove_field => ["headers", "@version"]
        add_field => { "description" => "Python_Java_ruby_perl " } 
  }
  mutate {
        split => {"description" =>  "_"}
  }

  if [description][4] {
    mutate {
     add_field => {"result" => "The 4 th field exists"}
    }   
  } else {

    mutate {
     add_field => {"result" => "The 4 th field  DOES NOT exists"}
    }   
 }

和控制台上的结果(因为没有第 4 个元素,它去else阻塞

{
           "host" => "0:0:0:0:0:0:0:1",
         "result" => "The 4 th field  DOES NOT exists",  <==== from else block
     "@timestamp" => 2020-01-14T19:35:41.013Z,
        "message" => "hello",
    "description" => [
        [0] "Python",
        [1] "Java",
        [2] "ruby",
        [3] "perl "
    ]
}

推荐阅读