-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathSearch.tsx
More file actions
699 lines (637 loc) · 21.8 KB
/
Search.tsx
File metadata and controls
699 lines (637 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
import {
useState,
useMemo,
ChangeEvent,
useCallback,
useEffect,
useRef,
useContext,
} from 'react';
import { Typography, AccordionSummary, Checkbox } from '@mui/material';
import { useTranslation } from 'react-i18next';
import { DataService, CollectionService } from '@/http';
import Icons from '@/components/icons/Icons';
import AttuGrid from '@/components/grid/Grid';
import EmptyCard from '@/components/cards/EmptyCard';
import CustomButton from '@/components/customButton/CustomButton';
import { getLabelDisplayedRows } from '@/pages/search/Utils';
import { useSearchResult, usePaginationHook } from '@/hooks';
import SearchGlobalParams from './SearchGlobalParams';
import VectorInputBox from './SearchInputBox';
import StatusIcon, { LoadingType } from '@/components/status/StatusIcon';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import OptimizedInput from '../data/OptimizedInput';
import PartitionsSelector from './PartitionsSelector';
import {
formatFieldType,
cloneObj,
generateVectorsByField,
saveCsvAs,
buildSearchParams,
} from '@/utils';
import SearchParams from './SearchParams';
import DataExplorer, { formatMilvusData } from './DataExplorer';
import {
SearchParams as SearchParamsType,
SearchSingleParams,
} from '../../types';
import { DYNAMIC_FIELD } from '@/consts';
import CollectionColHeader from '../CollectionColHeader';
import DataView from '@/components/DataView/DataView';
import type { GraphData, GraphNode } from '../../types';
import type { ColDefinitionsType } from '@/components/grid/Types';
import type {
CollectionObject,
CollectionFullObject,
VectorSearchResults,
} from '@server/types';
import {
SearchRoot,
InputArea,
AccordionsContainer,
StyledAccordion,
StyledAccordionDetails,
SearchControls,
SearchResults,
Toolbar,
Explorer,
CloseButton,
CheckboxRow,
LeftSection,
} from './StyledComponents';
import { authContext } from '@/context/Auth';
export interface CollectionDataProps {
collectionName: string;
collections: CollectionObject[];
searchParams: SearchParamsType;
setSearchParams: (params: SearchParamsType) => void;
}
const emptyExplorerData: GraphData = {
nodes: [],
links: [],
};
const Search = (props: CollectionDataProps) => {
// context
const { isManaged } = useContext(authContext);
// props
const { collections, collectionName, searchParams, setSearchParams } = props;
const collection = collections.find(
i => i.collection_name === collectionName
) as CollectionFullObject;
// UI states
const [tableLoading, setTableLoading] = useState<boolean>();
const [highlightField, setHighlightField] = useState<string>('');
const [explorerOpen, setExplorerOpen] = useState<boolean>(false);
const [localFilterValue, setLocalFilterValue] = useState<string>('');
// Use ref to track searchParams changes without causing re-renders
const searchParamsRef = useRef(searchParams);
searchParamsRef.current = searchParams;
// Memoize collection to avoid unnecessary re-renders
const memoizedCollection = useMemo(
() => collection,
[collection?.collection_name]
);
// Memoize selected fields to avoid recalculation
const selectedFields = useMemo(
() => searchParams.searchParams.filter(s => s.selected),
[searchParams.searchParams]
);
// Memoize enablePartitionsFilter
const enablePartitionsFilter = useMemo(
() => !collection.schema.enablePartitionKey,
[collection.schema.enablePartitionKey]
);
// translations
const { t: searchTrans } = useTranslation('search');
const { t: btnTrans } = useTranslation('btn');
// Sync local filter value with searchParams on mount and when searchParams change
useEffect(() => {
if (searchParams?.globalParams?.filter !== undefined) {
setLocalFilterValue(searchParams.globalParams.filter);
}
}, [searchParams?.globalParams?.filter]);
// UI functions - optimized with better dependencies
const handleExpand = useCallback(
(panel: string) => (event: ChangeEvent<{}>, expanded: boolean) => {
const s = cloneObj(searchParamsRef.current);
const target = s.searchParams.find((sp: SearchSingleParams) => {
return sp.field.name === panel;
});
if (target) {
target.expanded = expanded;
setSearchParams({ ...s });
}
},
[setSearchParams]
);
const handleSelect = useCallback(
(panel: string) => (event: ChangeEvent<{}>) => {
const s = cloneObj(searchParamsRef.current) as SearchParamsType;
const target = s.searchParams.find(sp => {
return sp.field.name === panel;
});
if (target) {
target.selected = !target.selected;
setSearchParams({ ...s });
}
},
[setSearchParams]
);
// update search params
const updateSearchParamCallback = useCallback(
(updates: SearchSingleParams, index: number) => {
const currentParams = searchParamsRef.current;
if (
JSON.stringify(updates) !==
JSON.stringify(currentParams.searchParams[index].params)
) {
const s = cloneObj(currentParams);
// update the searchParams
s.searchParams[index].params = updates;
setSearchParams({ ...s });
}
},
[setSearchParams]
);
// generate random vectors
const genRandomVectors = useCallback(() => {
const s = cloneObj(searchParamsRef.current) as SearchParamsType;
s.searchParams.forEach((sp: SearchSingleParams) => {
sp.data = generateVectorsByField(sp.field) as any;
});
setSearchParams({ ...s });
}, [setSearchParams]);
// on vector input change, update the search params
const onSearchInputChange = useCallback(
(anns_field: string, value: string) => {
const s = cloneObj(searchParamsRef.current) as SearchParamsType;
const target = s.searchParams.find((sp: SearchSingleParams) => {
return sp.anns_field === anns_field;
});
if (value !== target!.data) {
target!.data = value;
setSearchParams({ ...s });
}
},
[setSearchParams]
);
// on filter change - only update local state, not searchParams
const onFilterChange = useCallback((value: string) => {
setLocalFilterValue(value);
}, []);
// on partitions change
const onPartitionsChange = useCallback(
(value: any) => {
const s = cloneObj(searchParamsRef.current) as SearchParamsType;
s.partitions = value;
setSearchParams({ ...s });
},
[setSearchParams]
);
// set search result
const setSearchResult = useCallback(
(props: VectorSearchResults) => {
const { results, latency } = props;
const s = cloneObj(searchParamsRef.current) as SearchParamsType;
s.searchResult = results;
s.searchLatency = latency;
const newGraphData = formatMilvusData(
emptyExplorerData,
{ id: 'root' },
s.searchResult
);
s.graphData = newGraphData;
setSearchParams({ ...s });
},
[setSearchParams]
);
// execute search
const onSearchClicked = useCallback(async () => {
// Create a copy of current searchParams and update with current filter value
const s = cloneObj(searchParamsRef.current) as SearchParamsType;
s.globalParams.filter = localFilterValue;
// Update searchParams for future use
setSearchParams({ ...s });
const params = buildSearchParams(s);
setExplorerOpen(false);
setTableLoading(true);
try {
const res = await DataService.vectorSearchData(
s.collection.collection_name,
params
);
setTableLoading(false);
setSearchResult(res);
} catch (err) {
setTableLoading(false);
}
}, [localFilterValue, setSearchParams, setSearchResult]);
// execute explore
const onExploreClicked = useCallback(() => {
setExplorerOpen(explorerOpen => !explorerOpen);
}, []);
const onNodeClicked = useCallback(
async (node: GraphNode) => {
if (node.id === 'root') {
return;
}
setExplorerOpen(true);
setTableLoading(false);
const s = cloneObj(searchParamsRef.current);
const params = cloneObj(buildSearchParams(searchParamsRef.current));
try {
const query = await CollectionService.queryData(collectionName, {
expr: 'id == ' + node.id,
output_fields: ['*'],
});
// replace the vector data
params.data[0].data = query.data[0][params.data[0].anns_field];
const search = await DataService.vectorSearchData(
s.collection.collection_name,
params
);
const newGraphData = formatMilvusData(
s.graphData,
{ id: node.id, data: params.data[0].data },
search.results
);
s.graphData = newGraphData;
setSearchParams({ ...s });
} catch (err) {
console.log('err', err);
}
},
[collectionName, setSearchParams]
);
const searchResultMemo = useSearchResult(
(searchParams && searchParams.searchResult) || []
);
let primaryKeyField = 'id';
const {
pageSize,
handlePageSize,
setCurrentPage,
currentPage,
handleCurrentPage,
total,
data: result,
order,
orderBy,
handleGridSort,
} = usePaginationHook(searchResultMemo || []);
// reset
const onResetClicked = useCallback(() => {
const s = cloneObj(searchParamsRef.current) as SearchParamsType;
s.searchResult = null;
setSearchParams({ ...s });
setCurrentPage(0);
setLocalFilterValue(''); // Also reset local filter value
}, [setSearchParams, setCurrentPage]);
const onExplorerResetClicked = useCallback(() => {
onSearchClicked();
onExploreClicked();
}, [onSearchClicked, onExploreClicked]);
// Memoize colDefinitions with better dependencies
const colDefinitions: ColDefinitionsType[] = useMemo(() => {
if (!searchParams || !searchParams.collection) {
return [];
}
// collection fields, combine static and dynamic fields
const orderArray = [
primaryKeyField,
'id',
'score',
...searchParams.globalParams.output_fields,
];
return searchParams &&
searchParams.searchResult &&
searchParams.searchResult.length > 0
? Object.keys(searchParams.searchResult[0])
.sort((a, b) => {
const indexA = orderArray.indexOf(a);
const indexB = orderArray.indexOf(b);
return indexA - indexB;
})
.filter(item => {
// if primary key field name is id, don't filter it
const invalidItems = primaryKeyField === 'id' ? [] : ['id'];
return !invalidItems.includes(item) && orderArray.includes(item);
})
.map(key => {
return {
id: key,
align: 'left',
disablePadding: false,
label: key === DYNAMIC_FIELD ? searchTrans('dynamicFields') : key,
needCopy: key !== 'score',
headerFormatter: v => {
return (
<CollectionColHeader
def={v}
collection={memoizedCollection}
/>
);
},
formatter(_: any, cellData: any) {
const field = memoizedCollection.schema.fields.find(
f => f.name === key
);
return (
<DataView
type={field?.data_type || 'JSON'}
value={cellData}
/>
);
},
};
})
: [];
}, [
searchParams?.searchResult,
searchParams?.globalParams?.output_fields,
searchTrans,
memoizedCollection,
]);
// Memoize disable search logic
const { disableSearch, disableSearchTooltip } = useMemo(() => {
let disableSearch = false;
let disableSearchTooltip = '';
if (selectedFields.length === 0) {
disableSearch = true;
disableSearchTooltip = searchTrans('noSelectedVectorField');
}
const noDataInSelected = selectedFields.some(s => s.data === '');
if (noDataInSelected) {
disableSearch = true;
disableSearchTooltip = searchTrans('noVectorToSearch');
}
return { disableSearch, disableSearchTooltip };
}, [selectedFields, searchTrans]);
// methods
const handlePageChange = useCallback(
(e: any, page: number) => {
handleCurrentPage(page);
},
[handleCurrentPage]
);
// collection is not found or collection full object is not ready
if (
!searchParams ||
(searchParams && searchParams.searchParams.length === 0)
) {
return <StatusIcon type={LoadingType.CREATING} />;
}
const hasVectorIndex = searchParams.collection.schema?.hasVectorIndex;
const loaded = searchParams.collection.loaded;
if (!hasVectorIndex || !loaded) {
return (
<SearchRoot>
<EmptyCard
wrapperClass={`page-empty-card`}
icon={<Icons.load />}
text={searchTrans('loadCollectionFirst')}
/>
</SearchRoot>
);
}
return (
<SearchRoot>
{collection && (
<InputArea>
<LeftSection>
<AccordionsContainer>
{searchParams.searchParams.map((s, index: number) => {
const field = s.field;
return (
<StyledAccordion
key={`${collection.collection_name}-${field.name}`}
expanded={s.expanded}
onChange={handleExpand(field.name)}
className={highlightField === field.name ? 'highlight' : ''}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls={`${field.name}-content`}
id={`${field.name}-header`}
>
<CheckboxRow>
{searchParams.searchParams.length > 1 && (
<Checkbox
size="small"
checked={s.selected}
onChange={handleSelect(field.name)}
/>
)}
<div className="label">
<Typography
className={`field-name ${s.selected ? 'bold' : ''}`}
>
{field.is_function_output
? `${field.name}<=${
field.function!.input_field_names[0]
}`
: field.name}
</Typography>
<Typography className="vector-type">
{formatFieldType(field)}
<i>
{field.index &&
`${field.index.indexType}(${field.index.metricType})`}
</i>
</Typography>
</div>
</CheckboxRow>
</AccordionSummary>
<StyledAccordionDetails>
<VectorInputBox
searchParams={s}
onChange={onSearchInputChange}
collection={memoizedCollection}
type={field.is_function_output ? 'text' : 'vector'}
/>
<SearchParams
sx={{ pt: 1, mb: 1 }}
indexType={field.index.indexType}
searchParamsForm={s.params}
handleFormChange={(updates: {
[key in string]: number | string | boolean;
}) => {
updateSearchParamCallback(updates as any, index);
}}
isManaged={isManaged}
/>
</StyledAccordionDetails>
</StyledAccordion>
);
})}
{enablePartitionsFilter && (
<PartitionsSelector
collectionName={collectionName}
selected={searchParams.partitions}
setSelected={onPartitionsChange}
/>
)}
</AccordionsContainer>
<SearchControls>
<SearchGlobalParams
onSlideChange={(field: string) => {
setHighlightField(field);
}}
onSlideChangeCommitted={() => {
setHighlightField('');
}}
searchParams={searchParams}
handleFormChange={(params: any) => {
const s = cloneObj(searchParamsRef.current);
s.globalParams = params;
setSearchParams({ ...s });
}}
/>
<CustomButton
onClick={genRandomVectors}
size="small"
disabled={false}
className="genBtn"
sx={{
mb: 1,
}}
>
{btnTrans('example')}
</CustomButton>
<CustomButton
variant="contained"
size="small"
className="genBtn"
disabled={disableSearch}
tooltip={disableSearchTooltip}
tooltipPlacement="top"
onClick={onSearchClicked}
>
{btnTrans('searchMulti', {
number:
searchParams.collection.schema.vectorFields.length > 1
? `(${selectedFields.length})`
: '',
})}
</CustomButton>
</SearchControls>
</LeftSection>
<SearchResults>
<Toolbar>
<div className="left">
<OptimizedInput
value={localFilterValue}
onChange={onFilterChange}
onKeyDown={(e: any) => {
if (e.key === 'Enter') {
e.preventDefault();
onSearchClicked();
}
}}
disabled={explorerOpen}
fields={memoizedCollection.schema.scalarFields}
onSubmit={(expression: string) => {
setLocalFilterValue(expression);
// Don't immediately update searchParams, wait for search
}}
/>
</div>
<div className="right">
<CustomButton
onClick={onExploreClicked}
size="small"
disabled={
!searchParams.searchResult ||
searchParams.searchResult!.length === 0
}
className="btn"
startIcon={<Icons.magic classes={{ root: 'icon' }} />}
>
{btnTrans('explore')}
</CustomButton>
<CustomButton
className="btn"
disabled={result.length === 0}
onClick={() => {
saveCsvAs(
searchParams.searchResult,
`search_result_${searchParams.collection.collection_name}`
);
}}
startIcon={<Icons.download classes={{ root: 'icon' }} />}
>
{btnTrans('export')}
</CustomButton>
<CustomButton
className="btn"
onClick={
explorerOpen ? onExplorerResetClicked : onResetClicked
}
startIcon={<Icons.clear classes={{ root: 'icon' }} />}
>
{btnTrans('reset')}
</CustomButton>
</div>
</Toolbar>
{explorerOpen ? (
<Explorer>
<DataExplorer
data={searchParams.graphData}
onNodeClick={onNodeClicked}
/>
<CloseButton
onClick={() => {
setExplorerOpen(false);
}}
size="small"
startIcon={<Icons.clear classes={{ root: 'icon' }} />}
variant="contained"
>
{btnTrans('close')}
</CloseButton>
</Explorer>
) : (searchParams.searchResult &&
searchParams.searchResult.length > 0) ||
tableLoading ? (
<AttuGrid
sx={{
height: 'calc(100% - 64px)',
}}
toolbarConfigs={[]}
colDefinitions={colDefinitions}
rows={result}
rowCount={total}
primaryKey="rank"
page={currentPage}
tableHeaderHeight={45}
rowHeight={42}
openCheckBox={false}
onPageChange={handlePageChange}
rowsPerPage={pageSize}
setRowsPerPage={handlePageSize}
handleSort={handleGridSort}
orderBy={orderBy}
order={order}
labelDisplayedRows={getLabelDisplayedRows(
`(${searchParams.searchLatency} ms)`
)}
isLoading={tableLoading}
/>
) : (
<EmptyCard
wrapperClass={`page-empty-card`}
icon={<Icons.search />}
text={
searchParams.searchResult !== null
? searchTrans('empty')
: searchTrans('startTip')
}
/>
)}
</SearchResults>
</InputArea>
)}
</SearchRoot>
);
};
export default Search;