2 years ago
#69121

Mohsin Muazzam
How to iterate a flattened field array and access the flattened field object in elasticsearch
I have index with mapping as follows:
{
"mappings": {
"properties": {
"Forum Title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"normalizer": "lowercase_normalizer"
}
}
},
"Users": {
"type": "flattened"
},
"Comments": {
"type": "flattened"
}
}
}
}
In my use-case, if users leave the forum they cannot search and see new comments. Now the date left is present in one of the flattened User objects which I need to find. Is it possible to write a script that will give me the date left of a particular user which I will compare with the comment creation date. I tried to solve this scenario with nested objects first, but the problem is that both users and comments are treated as separate documents and scripts for one nested path does not have access to the parent or other nested document. And _source also is not available in elasticsearch 7+ versions which I am using.
{
"script": {
"script" : {
"source": "def user_date_left; for (def i=0; i < doc['users'].size(); i++){ if(doc['users.id'][i].value==params['user_id']){ user_date_left = doc['users.date_left'][i];} return doc['comments.date_created'] < user_date_left",
"params" : {
"user_id": 1244415493
}
}
}
}
EDIT: I think flattened field behaves the same as object field when array is concerned and to actually have relation between different fields in a array of objects a nested document must be used or either the schema needs to denormalized to have index of nested documents enriched with the fields of parent document. This will however occupy more space and the results will need to be aggregated into buckets.
elasticsearch
elasticsearch-painless
0 Answers
Your Answer