Sort Parent by Count of Unique Values of a Child Field

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 -

{
  "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!

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