# How to check if a doc has not a field

**URL:** <https://discuss.elastic.co/t/how-to-check-if-a-doc-has-not-a-field/91397>\
**Category:** Elasticsearch\
**Created:** [June 30, 2017, 9:45am UTC](https://discuss.elastic.co/t/how-to-check-if-a-doc-has-not-a-field/91397 "2017-06-30T09:45:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Riccardo\_Spampinato](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/riccardo_spampinato/32/18534_2.png) [@Riccardo\_Spampinato](https://discuss.elastic.co/u/Riccardo_Spampinato)\
**Post date:** [June 30, 2017, 9:45am UTC](https://discuss.elastic.co/t/how-to-check-if-a-doc-has-not-a-field/91397/1 "2017-06-30T09:45:44Z")

</div>

Hi everyone,  
I imported into `Elasticsearch` a set of emails (Enron corpus) which contains some email that has not the `to` header field (these emails have been sent to `undisclosed recipients`). However the indexing phase goes well, but when I try to query the database and get some fields of the emails and print them in the shell something goes wrong, because the query doesn't find the `to` field.

So I tried to put an `if` clause in order to print the `x-to` field whenever the `to` one is missing.

This is the code:

```
s = Search(using=client, index="enron_test")
s = s.source(['message_body', 'from', 'to', 'x-to'])

response = s.execute()

for hit in response['hits']['hits']:
    print("FROM: " + hit['_source']['from'])
    print("TO: "),
    if hit['_source']['to'] not in response['hits']['hits']:
        print(hit['_source']['x-to'])
    else:
        print(hit['_source']['to'])
    print("\n" + hit['_source']['message_body'])
    print(line + "\n")

```

It gives me this error:

```
 Traceback (most recent call last):
 File "rico.py", line 24, in <module>
 if hit['_source']['to'] not in response['hits']['hits']:
 File "/home/rico/.local/lib/python2.7/site-packages/elasticsearch_dsl/utils.py", line 125, in __getitem__
 return _wrap(self._d_[key])
 KeyError: 'to'

```

Anyone can help me in solving this problem?

---

<div class="post-metadata">

**Author:** ![colings86](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/colings86/32/44960_2.png) [@colings86](https://discuss.elastic.co/u/colings86)\
**Post date:** [June 30, 2017, 12:32pm UTC](https://discuss.elastic.co/t/how-to-check-if-a-doc-has-not-a-field/91397/2 "2017-06-30T12:32:54Z")

</div>

I think your if condition should be `if 'to' not in hit['_source]`

---

<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:** [July 28, 2017, 12:33pm UTC](https://discuss.elastic.co/t/how-to-check-if-a-doc-has-not-a-field/91397/3 "2017-07-28T12:33:13Z")

</div>

Closed on July 28, 2017, 12:33pm UTC

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