I want to fetch latest visits of patients that belongs to a doctor.
Example data:
{
doctor_id:"abcd",
"patient_id":"pat1",
"created_date":"2022-08-30T15:26:19.171Z"
"patient_data":"some data belongs to patient"
},
{
doctor_id:"abcd",
"patient_id":"pat1",
"created_date":"2022-08-29T15:26:19.171Z"
"patient_data":"some data belongs to patient"
},
{
doctor_id:"abcd",
"patient_id":"pat2",
"created_date":"2022-08-30T15:26:19.171Z"
"patient_data":"some data belongs to patient"
},
{
doctor_id:"abcd",
"patient_id":"pat2",
"created_date":"2022-08-29T15:26:19.171Z"
"patient_data":"some data belongs to patient"
},
Is it possible to get the latest record of each patient:
{
doctor_id:"abcd",
"patient_id":"pat1",
"created_date":"2022-08-30T15:26:19.171Z"
"patient_data":"some data belongs to patient"
},
{
doctor_id:"abcd",
"patient_id":"pat2",
"created_date":"2022-08-30T15:26:19.171Z"
"patient_data":"some data belongs to patient"
}
What should I follow to do get results like this.
UPDATE: I am using below query now:
{
"query":{
"bool": {
"must": [
{
"term": {
"doctor_id.keyword": "abcd"
}
}
]
}
},
"aggs": {
"latest_created_date": {
"top_hits": {
"sort": [
{
"created_date": {
"order": "desc"
}
}
],
"size": 1
}
}
}
}
}
Using this query, in the aggregations, I am only seeing one record which is the latest by date.
I want atleast one record of each patient by latest date.