# Sort Parent by Count of Unique Values of a Child Field

**URL:** <https://discuss.elastic.co/t/sort-parent-by-count-of-unique-values-of-a-child-field/289333>\
**Category:** Elasticsearch\
**Created:** [November 16, 2021, 1:49pm UTC](https://discuss.elastic.co/t/sort-parent-by-count-of-unique-values-of-a-child-field/289333 "2021-11-16T13:49:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![amarjotbhullar](https://avatars.discourse-cdn.com/v4/letter/a/e68b1a/32.png) [@amarjotbhullar](https://discuss.elastic.co/u/amarjotbhullar)\
**Post date:** [November 16, 2021, 1:49pm UTC](https://discuss.elastic.co/t/sort-parent-by-count-of-unique-values-of-a-child-field/289333/1 "2021-11-16T13:49:09Z")

</div>

Hi,  
I am currently working on a feature where I have a parent child relationship between driver and trips taken by driver. I need to sort drivers by unique count of no. of cars driven irrespective of number of trips taken by driver.

Here is my mapping -

```auto
{
  "dynamic" : "false",
  "_source" : {
    "enabled" : true
  },
  "properties" : {
    "driver" : {
      "properties": {
        "driverId": {
          "type": "keyword"
        },
        "driverName": {
          "type": "text"
        },
        "driverDateOfBirth": {
          "type": "date"
        }
      }
    },
    "trips" : {
      "properties": {
        "tripId": {
          "type": "keyword"
        },
        "driverId": {
          "type": "keyword"
        },
        "carId": {
          "type": "text"
        },
        "tripDate": {
          "type": "date"
        }
      }
    },
    "my_join_field" : {
      "type" : "join",
      "relations" : {
        "driver" : [
          "trips"
        ]
      }
    }
  }
}

```

I need to sort driver by unique count of carId property of trips.

Now I understand we cannot directly sort parent by child and for my other sorts I am using function\_score query with script\_score to modify child score using child fields and using sum of all child scores as parent scores. But, for this scenario I do not have ideas as to how to solve the same.

Please help this innocent engineer you kindhearted people. Thanks!

---

<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:** [December 14, 2021, 1:49pm UTC](https://discuss.elastic.co/t/sort-parent-by-count-of-unique-values-of-a-child-field/289333/2 "2021-12-14T13:49:26Z")

</div>

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