# GROK pattern query

**URL:** <https://discuss.elastic.co/t/grok-pattern-query/177464>\
**Category:** Logstash\
**Created:** [April 18, 2019, 12:50pm UTC](https://discuss.elastic.co/t/grok-pattern-query/177464 "2019-04-18T12:50:05Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![MiddlewareTeam](https://avatars.discourse-cdn.com/v4/letter/m/8e8cbc/32.png) [@MiddlewareTeam](https://discuss.elastic.co/u/MiddlewareTeam)\
**Post date:** [April 18, 2019, 12:50pm UTC](https://discuss.elastic.co/t/grok-pattern-query/177464/1 "2019-04-18T12:50:05Z")

</div>

I have log as below:

nbresp:500 ~ nbresp1:406 ~ nbresp2: ~ nbresp3:409

I am using GROK pattern as below

%{WORD}:%{WORD:nbresp} ~ %{WORD}:%{WORD:nbresp1} ~ %{WORD}:%{WORD:nbresp2} ~ %{WORD}:%{WORD:nbresp3} ~

which is working exactly fine till nbresp1 but giving grok pattern failure while nbresp2 as there is no value for it. The value of this field varies and sometime it may not give any output like above which becomes blank, I have to provide structural data to ES but as it is failing I can not parse data properly. Can someone please help me how to set grok pattern in this case?

---

<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:** [April 18, 2019, 1:47pm UTC](https://discuss.elastic.co/t/grok-pattern-query/177464/2 "2019-04-18T13:47:01Z")

</div>

You can surround a field with ( and )? to make it optional. For example

```
input { generator { count => 1 message => 'nbresp:500 ~ nbresp1:406 ~ nbresp2:400 ~ nbresp3:409' } }
input { generator { count => 1 message => 'nbresp:500 ~ nbresp1:406 ~ nbresp2: ~ nbresp3:409' } }

filter {
    grok { match => { "message" => "%{WORD}:%{WORD:nbresp} ~ %{WORD}:%{WORD:nbresp1} ~ %{WORD}:(%{WORD:nbresp2})? ~ %{WORD}:%{WORD:nbresp3}" } }
}
```

---

<div class="post-metadata">

**Author:** ![MiddlewareTeam](https://avatars.discourse-cdn.com/v4/letter/m/8e8cbc/32.png) [@MiddlewareTeam](https://discuss.elastic.co/u/MiddlewareTeam)\
**Post date:** [April 25, 2019, 9:40am UTC](https://discuss.elastic.co/t/grok-pattern-query/177464/3 "2019-04-25T09:40:21Z")

</div>

Thanks Badger,

This worked as expected. Thanks again for your help!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [May 23, 2019, 9:40am UTC](https://discuss.elastic.co/t/grok-pattern-query/177464/4 "2019-05-23T09:40:33Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
