I need to sort documents in my elastic index using a field inside an array in that document. Document structure looks like this,
{
'name':'xxxxx',
'comments':[
{comment: 'xxxxx', 'commentDate':'yyyy-MM-dd HH:mm:ss', 'id':1},
{comment: 'xxxxx', 'commentDate':'yyyy-MM-dd HH:mm:ss', 'id':2}
]
}
What I want to do is sort the documents based on the commentDate field to get the documents with latest comments first. So far I've think of keeping separate field inside the document to track the last comment date. So the document becomes,
{
'name':'xxxxx',
'comments':[
{comment: 'xxxxx', 'commentDate':'yyyy-MM-dd HH:mm:ss', 'id':1},
{comment: 'xxxxx', 'commentDate':'yyyy-MM-dd HH:mm:ss', 'id':2}
],
'lastCommentDate': 'yyyy-MM-dd HH:mm:ss'
}
I'd like to know whether is this the best way of doing this or is it possible to do this using script sort without changing the index?
I'm using Elastic API for Java and it would be very much appreciated if you can show me how to do this without changing the index. Also, I want to get the sorted data set directly from ES, so sorting after fetching data is not what I'm looking for
Elastic version : 5.1.1