# How to drop any fields containing the word "PublicKey" from logstash

**URL:** https://discuss.elastic.co/t/how-to-drop-any-fields-containing-the-word-publickey-from-logstash/369809
**Category:** Logstash
**Created:** [October 30, 2024, 12:11pm UTC](https://discuss.elastic.co/t/how-to-drop-any-fields-containing-the-word-publickey-from-logstash/369809 "2024-10-30T12:11:03Z")
**Posts on this page:** 1
**Showing post:** 4

<div class="post-metadata">

### Author: ![Badger](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/badger/32/25190_2.png) [@Badger](https://discuss.elastic.co/u/Badger)
#### Post date: [November 5, 2024, 11:07am UTC](https://discuss.elastic.co/t/how-to-drop-any-fields-containing-the-word-publickey-from-logstash/369809/4 "2024-11-05T11:07:00Z")

</div>

My original answer just tests the top-level fields. If you want to remove fields nested inside of fields then try

```
    ruby {
        init => '
            def doSomething(object, name, event)
                if object # Remove this if your use-case needs to process nil objects
                    # If we need to handle non-leaf nodes then test this first
                    if name.include?("PublicKey")
                        event.remove(name)
                    elsif object.kind_of?(Hash) and object != {}
                        object.each { |k, v| doSomething(v, "#{name}[#{k}]", event) }
                    elsif object.kind_of?(Array) and object != []
                        object.each_index { |i|
                            doSomething(object[i], "#{name}[#{i}]", event)
                        }
                    end
                end
            end

        '
        code => '
            event.to_hash.each { |k, v|
                doSomething(v, "[#{k}]", event)
            }
        '
    }

```

It seems like half the times I use this type of loop I find something that breaks my [original version](https://discuss.elastic.co/t/to-exclude-around-350-fields-in-json-in-logstash/239019/6) and [variants](https://discuss.elastic.co/t/how-to-exclude-xml-json-key-value-if-key-length-is-greater-than-15-char-and-value-length-is-greater-than-100-char/270248/8). This time it was the need to run the test against non-leaf nodes 🤣

---

_[View the full topic](https://discuss.elastic.co/t/how-to-drop-any-fields-containing-the-word-publickey-from-logstash/369809)._
