# Comparing Date Fields of Nested Objects

**URL:** https://discuss.elastic.co/t/comparing-date-fields-of-nested-objects/278222
**Category:** Elasticsearch
**Tags:** painless
**Created:** [July 8, 2021, 10:33pm UTC](https://discuss.elastic.co/t/comparing-date-fields-of-nested-objects/278222 "2021-07-08T22:33:04Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Fatih\_Kurnaz](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/fatih_kurnaz/32/83540_2.png) [@Fatih\_Kurnaz](https://discuss.elastic.co/u/Fatih_Kurnaz)
#### Post date: [July 8, 2021, 10:33pm UTC](https://discuss.elastic.co/t/comparing-date-fields-of-nested-objects/278222/1 "2021-07-08T22:33:04Z")

</div>

Hi Everyone;

Here my painless script;

```auto
  "script_fields": {
    "seen": {
      "script": {
        "source": """
for (view in params['_source']['viewing_appointments']) { 
          if (new Date().getTime() - view.viewing_date.value.toInstant().toEpochMilli()) {
          return true;
          }
        } return false;
"""
      }
    }
  }

```

Please note that;  
mapping type of "viewing\_appointments" is NESTED

Since its type is nested, I have to access inner values of it by using "\_source" method instead of "doc".  
However; when I use "\_source" method, Elasticsearch takes values at "JSON" format  
and seems type of "viewing\_date" as "String"  
and throws error when I try to compare it with "Date".

How can I deal with this problem.  
Thanks a lot ...

---

<div class="post-metadata">

### Author: ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)
#### Post date: [July 9, 2021, 8:27am UTC](https://discuss.elastic.co/t/comparing-date-fields-of-nested-objects/278222/2 "2021-07-09T08:27:13Z")

</div>

Two solutions. First parse the string from the `_source` to a date, for example using `ZonedDateTime.parse`.

Second: You you use a mapping parameter to have the. field also in your root document, see [Nested field type | Elasticsearch Guide [7.13] | Elastic](https://www.elastic.co/guide/en/elasticsearch/reference/7.13/nested.html#nested-params)

Out of curiousity: Why is this a nested field, if you do not store this within an array? (according to your script) Is this needed at all?

---

<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: [August 6, 2021, 8:27am UTC](https://discuss.elastic.co/t/comparing-date-fields-of-nested-objects/278222/3 "2021-08-06T08:27:58Z")

</div>

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