How to access parent field from nested scope in Elasticsearch query?

Viewed 158

I have the following object where the key is my group ids and the values are relevant codes for each group.

Obj:

{
   "1" : [1,2,3],
   "2" : [4,5,6]
}

I convert all keys to a number array and iterate them in my query.

I wanted to add a filter which will take only codes that intersect with my values but seems that the nested fields are not familiar with my parent iterated group id.

Here is my query -> marked the problematic part

myFunc(myObj) {
groupIds:Array<number> = getAllKeysFromObject(myObj); //GETTING ALL GROUP IDS - will return [1,2]
  return {
        _source: false,
        docvalue_fields: [{
            field: 'group_id',
            format: 'use_field_mapping',
        }],
        query: {
            bool: {
                filter: [{
                    terms: {group_id: groupIds}, //HERE ARE THE GROUP IDS
                }, {
                    nested: {
                        inner_hits: {
                            _source: false,
                            docvalue_fields: [{
                                field: 'products.code',
                                format: 'use_field_mapping',
                            },  
                            ],
                            size: 2,
                            sort: [{[`products.somefield`]: 'desc'}],
                        },
                        path: 'products',
                        query: {
                            bool: {
                              must: [
                                {
                                  terms: {
                                    'products.code': myObj[group_id], //THIS DOES NOT WORK as group_id is not recognised. Would like for group_id=1 to have here [1,2,3] and for next iteration of group_id=2 to get [4,5,6]
                                  },
                                },
                              ],
                            },
                          },
                        },
                      },
                    ],
                  },
                },
        size: 5,
    };
0 Answers
Related