代码之家  ›  专栏  ›  技术社区  ›  KARAN SHAH

使用Logstash解析XML文件

  •  2
  • KARAN SHAH  · 技术社区  · 7 年前

    我正在尝试解析Logstash中的XML文件。我想使用XPath来解析XML中的文档。因此,当我运行配置文件时,数据加载到 elasticsearch 但这不是我想要加载数据的方式。加载的数据 弹性搜索 是xml文档中的每一行

    我的XML文件的结构

    enter image description here

    我想要实现的目标:

    在elasticsearch中创建存储以下内容的字段

    ID =1
    Name = "Finch"
    

    我的配置文件:

    input{
        file{
            path => "C:\Users\186181152\Downloads\stations.xml"
            start_position => "beginning"
            sincedb_path => "/dev/null"
            exclude => "*.gz"
            type => "xml"
        }
    }
    filter{
        xml{
            source => "message"
            store_xml => false
            target => "stations"
            xpath => [
                "/stations/station/id/text()", "station_id",
                "/stations/station/name/text()", "station_name"
            ]
        }
    }
    
    output{
        elasticsearch{
            codec => json
            hosts => "localhost"
            index => "xmlns"
        }
        stdout{
            codec => rubydebug
        }
    }
    

    Logstash中的输出:

    {
        "station_name" => "%{station_name}",
        "path" => "C:\Users\186181152\Downloads\stations.xml",
        "@timestamp" => 2018-02-09T04:03:12.908Z,
        "station_id" => "%{station_id}",
        "@version" => "1",
        "host" => "BW",
        "message" => "\t\r",
        "type" => "xml"
    }
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Daniel Rotter    5 年前

    多行过滤器允许将xml文件创建为单个事件,我们可以使用xml过滤器或xpath解析xml以吸收elasticsearch中的数据。 在多行过滤器中,我们提到了logstash用来扫描xml文件的模式(在下面的示例中)。一旦模式匹配,之后的所有条目将被视为单个事件。

    以下是我的数据的工作配置文件示例

    input {
        file {
            path => "C:\Users\186181152\Downloads\stations3.xml"
            start_position => "beginning"
            sincedb_path => "/dev/null"
            exclude => "*.gz"
            type => "xml"
            codec => multiline {
                pattern => "<stations>" 
                negate => "true"
                what => "previous"
            }
        }
    }
    
    filter {
        xml {
            source => "message"
            store_xml => false
            target => "stations"
            xpath => [
                "/stations/station/id/text()", "station_id",
                "/stations/station/name/text()", "station_name"
            ]
        }
    }
    
    output {
        elasticsearch {
            codec => json
            hosts => "localhost"
            index => "xmlns24"
        }
        stdout {
            codec => rubydebug
        }
    }