Search by max(time) possible?

if parent(p) with id 1 has two children(c): 1,2

time 111 is the first logs for parent-1
whereas time 114 is the latest log values for parent-1
is there a way to get the latest log values for parent-1,

records looks something like this:
{p:1,c:1,k:v,time:114}, {p:1,c:2,k:v,time:114}, {p:1,c:1,k:v,time:111}, {p:1,c:2,k:v,time:111}

SQL would be something like:
select * from log_index where p=1 and time=(select max(time) where p=1)

If you just need a single result of the max time, you can use nested aggregation with max aggregation.

Provided that you have index with nested fields:

{
    "mappings": {
        "_doc": {
            "properties": {
                "p": {
                    "type": "keyword"
                },
                "p_children": {
                    "type": "nested"
                }
            }
        }
    }
}

You index your documents:

POST my_index/_doc/_bulk?refresh=true
{ "index" : {"_id" : "1" } }
{"p":"p1", "p_children": [{"c":1,"k":"v","time":111}, {"c":2,"k":"v","time":114}]}
{ "index" : {"_id" : "2" } }
{"p":"p2", "p_children": [{"c":1,"k":"v","time":200}, {"c":2,"k":"v","time":201}]}

You can run the following nested aggregation to get a max time of the children of p1:

{
	"size": 0,
	"query" : {
		"match" : {"p" : "p1"}
	}, 
    "aggs": {
        "max_time_p": {
            "nested": {
                "path": "p_children"
            },
            "aggs": {
                "max_time": {
                    "max": {
                        "field": "p_children.time"
                    }
                }
            }
        }
    }
}

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