Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix flatten hit modify original array #9347

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
2 changes: 2 additions & 0 deletions changelogs/fragments/9347.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fix:
- Flatten hit modify original array ([#9347](https://github.com/opensearch-project/OpenSearch-Dashboards/pull/9347))
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ function flattenHit(indexPattern: IndexPattern, hit: Record<string, any>, deep:

if (hasValidMapping || isValue) {
if (!flat[key]) {
flat[key] = val;
// Create a new array to avoid modifying the original array when pushing elements
flat[key] = Array.isArray(val) ? [...val] : val;
} else if (Array.isArray(flat[key])) {
flat[key].push(val);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
* under the License.
*/

import { map, last } from 'lodash';
import { map, last, cloneDeep } from 'lodash';

import { IndexPattern } from './index_pattern';

Expand Down Expand Up @@ -319,4 +319,77 @@ describe('IndexPatternWithDataSource', () => {
expect(indexPattern.getSaveObjectReference()[0]?.name).toEqual('dataSource');
});
});

describe('flattenHit', () => {
test('should not modify original hit', () => {
const nestedArrayIndexPattern = new IndexPattern({
spec: {
id: 'test-nested-array',
type: 'index-pattern',
fields: {
'nested_test1.d_values': {
count: 0,
name: 'nested_test1.d_values',
type: 'number',
esTypes: ['double'],
scripted: false,
searchable: true,
aggregatable: true,
readFromDocValues: true,
subType: {
nested: {
path: 'nested_test1',
},
},
},
'nested_test1.s_entry': {
count: 0,
name: 'nested_test1.s_entry',
type: 'string',
esTypes: ['keyword'],
scripted: false,
searchable: true,
aggregatable: true,
readFromDocValues: true,
subType: {
nested: {
path: 'nested_test1',
},
},
},
},
},
savedObjectsClient: {} as any,
fieldFormats: fieldFormatsMock,
shortDotsEnable: false,
metaFields: [],
});

const hit = {
_index: 'test-nested-array',
_id: 'JPas2pQBluzwIEYCwD0y',
_score: 1,
_source: {
nested_test1: [
{
d_values: [0.1, 0.2],
s_entry: '4',
},
{
d_values: [0.3, 0.4],
s_entry: '5',
},
{
d_values: [0.5, 0.6],
s_entry: '6',
},
],
},
};
const hitClone = cloneDeep(hit);
nestedArrayIndexPattern.flattenHit(hit);

expect(hit).toEqual(hitClone);
});
});
});
Loading