VectorSearch.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. import { TextField, Typography } from '@material-ui/core';
  2. import { useTranslation } from 'react-i18next';
  3. import { useNavigationHook } from '../../hooks/Navigation';
  4. import { ALL_ROUTER_TYPES } from '../../router/Types';
  5. import CustomSelector from '../../components/customSelector/CustomSelector';
  6. import { useCallback, useEffect, useMemo, useState } from 'react';
  7. import SearchParams from './SearchParams';
  8. import { DEFAULT_METRIC_VALUE_MAP } from '../../consts/Milvus';
  9. import { FieldOption, SearchResultView, VectorSearchParam } from './Types';
  10. import MilvusGrid from '../../components/grid/Grid';
  11. import EmptyCard from '../../components/cards/EmptyCard';
  12. import icons from '../../components/icons/Icons';
  13. import { usePaginationHook } from '../../hooks/Pagination';
  14. import CustomButton from '../../components/customButton/CustomButton';
  15. import SimpleMenu from '../../components/menu/SimpleMenu';
  16. import { TOP_K_OPTIONS } from './Constants';
  17. import { Option } from '../../components/customSelector/Types';
  18. import { CollectionHttp } from '../../http/Collection';
  19. import { CollectionData, DataTypeEnum } from '../collections/Types';
  20. import { IndexHttp } from '../../http/Index';
  21. import { getVectorSearchStyles } from './Styles';
  22. import { parseValue } from '../../utils/Insert';
  23. import {
  24. classifyFields,
  25. getDefaultIndexType,
  26. getEmbeddingType,
  27. getNonVectorFieldsForFilter,
  28. getVectorFieldOptions,
  29. transferSearchResult,
  30. } from '../../utils/search';
  31. import { ColDefinitionsType } from '../../components/grid/Types';
  32. import Filter from '../../components/advancedSearch';
  33. import { Field } from '../../components/advancedSearch/Types';
  34. import { useLocation } from 'react-router-dom';
  35. import { parseLocationSearch } from '../../utils/Format';
  36. const VectorSearch = () => {
  37. useNavigationHook(ALL_ROUTER_TYPES.SEARCH);
  38. const location = useLocation();
  39. // i18n
  40. const { t: searchTrans } = useTranslation('search');
  41. const { t: btnTrans } = useTranslation('btn');
  42. const classes = getVectorSearchStyles();
  43. // data stored inside the component
  44. const [tableLoading, setTableLoading] = useState<boolean>(false);
  45. const [collections, setCollections] = useState<CollectionData[]>([]);
  46. const [selectedCollection, setSelectedCollection] = useState<string>('');
  47. const [fieldOptions, setFieldOptions] = useState<FieldOption[]>([]);
  48. // fields for advanced filter
  49. const [filterFields, setFilterFields] = useState<Field[]>([]);
  50. const [selectedField, setSelectedField] = useState<string>('');
  51. // search params form
  52. const [searchParam, setSearchParam] = useState<{ [key in string]: number }>(
  53. {}
  54. );
  55. // search params disable state
  56. const [paramDisabled, setParamDisabled] = useState<boolean>(true);
  57. // use null as init value before search, empty array means no results
  58. const [searchResult, setSearchResult] = useState<SearchResultView[] | null>(
  59. null
  60. );
  61. // default topK is 100
  62. const [topK, setTopK] = useState<number>(100);
  63. const [expression, setExpression] = useState<string>('');
  64. const [vectors, setVectors] = useState<string>('');
  65. const {
  66. pageSize,
  67. handlePageSize,
  68. currentPage,
  69. handleCurrentPage,
  70. total,
  71. data: result,
  72. } = usePaginationHook(searchResult || []);
  73. const collectionOptions: Option[] = useMemo(
  74. () =>
  75. collections.map(c => ({
  76. label: c._name,
  77. value: c._name,
  78. })),
  79. [collections]
  80. );
  81. const outputFields: string[] = useMemo(() => {
  82. const fields =
  83. collections.find(c => c._name === selectedCollection)?._fields || [];
  84. // vector field can't be output fields
  85. const invalidTypes = ['BinaryVector', 'FloatVector'];
  86. const nonVectorFields = fields.filter(
  87. field => !invalidTypes.includes(field._fieldType)
  88. );
  89. return nonVectorFields.map(f => f._fieldName);
  90. }, [selectedCollection, collections]);
  91. const primaryKeyField = useMemo(() => {
  92. const selectedCollectionInfo = collections.find(
  93. c => c._name === selectedCollection
  94. );
  95. const fields = selectedCollectionInfo?._fields || [];
  96. return fields.find(f => f._isPrimaryKey)?._fieldName;
  97. }, [selectedCollection, collections]);
  98. const colDefinitions: ColDefinitionsType[] = useMemo(() => {
  99. /**
  100. * id represents primary key, score represents distance
  101. * since we transfer score to distance in the view, and original field which is primary key has already in the table
  102. * we filter 'id' and 'score' to avoid redundant data
  103. */
  104. return searchResult && searchResult.length > 0
  105. ? Object.keys(searchResult[0])
  106. .filter(item => {
  107. // if primary key field name is id, don't filter it
  108. const invalidItems =
  109. primaryKeyField === 'id' ? ['score'] : ['id', 'score'];
  110. return !invalidItems.includes(item);
  111. })
  112. .map(key => ({
  113. id: key,
  114. align: 'left',
  115. disablePadding: false,
  116. label: key,
  117. }))
  118. : [];
  119. }, [searchResult, primaryKeyField]);
  120. const {
  121. metricType,
  122. indexType,
  123. indexParams,
  124. fieldType,
  125. embeddingType,
  126. selectedFieldDimension,
  127. } = useMemo(() => {
  128. if (selectedField !== '') {
  129. // field options must contain selected field, so selectedFieldInfo will never undefined
  130. const selectedFieldInfo = fieldOptions.find(
  131. f => f.value === selectedField
  132. );
  133. const index = selectedFieldInfo?.indexInfo;
  134. const embeddingType = getEmbeddingType(selectedFieldInfo!.fieldType);
  135. const metric =
  136. index?._metricType || DEFAULT_METRIC_VALUE_MAP[embeddingType];
  137. const indexParams = index?._indexParameterPairs || [];
  138. const dim = selectedFieldInfo?.dimension || 0;
  139. return {
  140. metricType: metric,
  141. indexType: index?._indexType || getDefaultIndexType(embeddingType),
  142. indexParams,
  143. fieldType: DataTypeEnum[selectedFieldInfo?.fieldType!],
  144. embeddingType,
  145. selectedFieldDimension: dim,
  146. };
  147. }
  148. return {
  149. metricType: '',
  150. indexType: '',
  151. indexParams: [],
  152. fieldType: 0,
  153. embeddingType: DataTypeEnum.FloatVector,
  154. selectedFieldDimension: 0,
  155. };
  156. }, [selectedField, fieldOptions]);
  157. /**
  158. * vector value validation
  159. * @return whether is valid
  160. */
  161. const vectorValueValid = useMemo(() => {
  162. // if user hasn't input value or not select field, don't trigger validation check
  163. if (vectors === '' || selectedFieldDimension === 0) {
  164. return true;
  165. }
  166. const value = parseValue(vectors);
  167. const isArray = Array.isArray(value);
  168. return isArray && value.length === selectedFieldDimension;
  169. }, [vectors, selectedFieldDimension]);
  170. const searchDisabled = useMemo(() => {
  171. /**
  172. * before search, user must:
  173. * 1. enter vector value, it should be an array and length should be equal to selected field dimension
  174. * 2. choose collection and field
  175. * 3. set extra search params
  176. */
  177. const isInvalid =
  178. vectors === '' ||
  179. selectedCollection === '' ||
  180. selectedField === '' ||
  181. paramDisabled ||
  182. !vectorValueValid;
  183. return isInvalid;
  184. }, [
  185. paramDisabled,
  186. selectedField,
  187. selectedCollection,
  188. vectors,
  189. vectorValueValid,
  190. ]);
  191. // fetch data
  192. const fetchCollections = useCallback(async () => {
  193. const collections = await CollectionHttp.getCollections();
  194. setCollections(collections);
  195. }, []);
  196. const fetchFieldsWithIndex = useCallback(
  197. async (collectionName: string, collections: CollectionData[]) => {
  198. const fields =
  199. collections.find(c => c._name === collectionName)?._fields || [];
  200. const indexes = await IndexHttp.getIndexInfo(collectionName);
  201. const { vectorFields, nonVectorFields } = classifyFields(fields);
  202. // only vector type fields can be select
  203. const fieldOptions = getVectorFieldOptions(vectorFields, indexes);
  204. setFieldOptions(fieldOptions);
  205. if (fieldOptions.length > 0) {
  206. // set first option value as default field value
  207. const [{ value: defaultFieldValue }] = fieldOptions;
  208. setSelectedField(defaultFieldValue as string);
  209. }
  210. // only non vector type fields can be advanced filter
  211. const filterFields = getNonVectorFieldsForFilter(nonVectorFields);
  212. setFilterFields(filterFields);
  213. },
  214. []
  215. );
  216. useEffect(() => {
  217. fetchCollections();
  218. }, [fetchCollections]);
  219. // get field options with index when selected collection changed
  220. useEffect(() => {
  221. if (selectedCollection !== '') {
  222. fetchFieldsWithIndex(selectedCollection, collections);
  223. }
  224. }, [selectedCollection, collections, fetchFieldsWithIndex]);
  225. // set default collection value if is from overview page
  226. useEffect(() => {
  227. if (location.search && collections.length > 0) {
  228. const { collectionName } = parseLocationSearch(location.search);
  229. // collection name validation
  230. const isNameValid = collections
  231. .map(c => c._name)
  232. .includes(collectionName);
  233. isNameValid && setSelectedCollection(collectionName);
  234. }
  235. }, [location, collections]);
  236. // icons
  237. const VectorSearchIcon = icons.vectorSearch;
  238. const ResetIcon = icons.refresh;
  239. const ArrowIcon = icons.dropdown;
  240. // methods
  241. const handlePageChange = (e: any, page: number) => {
  242. handleCurrentPage(page);
  243. };
  244. const handleReset = () => {
  245. /**
  246. * reset search includes:
  247. * 1. reset vectors
  248. * 2. reset selected collection and field
  249. * 3. reset search params
  250. * 4. reset advanced filter expression
  251. * 5. clear search result
  252. */
  253. setVectors('');
  254. setSelectedField('');
  255. setSelectedCollection('');
  256. setSearchResult(null);
  257. setFilterFields([]);
  258. setExpression('');
  259. };
  260. const handleSearch = async (topK: number, expr = expression) => {
  261. const searhParamPairs = [
  262. // dynamic search params
  263. {
  264. key: 'params',
  265. value: JSON.stringify(searchParam),
  266. },
  267. {
  268. key: 'anns_field',
  269. value: selectedField,
  270. },
  271. {
  272. key: 'topk',
  273. value: topK,
  274. },
  275. {
  276. key: 'metric_type',
  277. value: metricType,
  278. },
  279. ];
  280. const params: VectorSearchParam = {
  281. output_fields: outputFields,
  282. expr,
  283. search_params: searhParamPairs,
  284. vectors: [parseValue(vectors)],
  285. vector_type: fieldType,
  286. };
  287. setTableLoading(true);
  288. try {
  289. const res = await CollectionHttp.vectorSearchData(
  290. selectedCollection,
  291. params
  292. );
  293. setTableLoading(false);
  294. const result = transferSearchResult(res.results);
  295. setSearchResult(result);
  296. } catch (err) {
  297. setTableLoading(false);
  298. }
  299. };
  300. const handleAdvancedFilterChange = (expression: string) => {
  301. setExpression(expression);
  302. if (!searchDisabled) {
  303. handleSearch(topK, expression);
  304. }
  305. };
  306. const handleVectorChange = (value: string) => {
  307. setVectors(value);
  308. };
  309. return (
  310. <section className="page-wrapper">
  311. {/* form section */}
  312. <form className={classes.form}>
  313. {/**
  314. * vector value textarea
  315. * use field-params class because it also has error msg if invalid
  316. */}
  317. <fieldset className="field field-params">
  318. <Typography className="text">
  319. {searchTrans('firstTip', {
  320. dimensionTip:
  321. selectedFieldDimension !== 0
  322. ? `(dimension: ${selectedFieldDimension})`
  323. : '',
  324. })}
  325. </Typography>
  326. <TextField
  327. className="textarea"
  328. InputProps={{
  329. classes: {
  330. root: 'textfield',
  331. multiline: 'multiline',
  332. },
  333. }}
  334. multiline
  335. rows={5}
  336. placeholder={searchTrans('vectorPlaceholder')}
  337. value={vectors}
  338. onChange={(e: React.ChangeEvent<{ value: unknown }>) => {
  339. handleVectorChange(e.target.value as string);
  340. }}
  341. />
  342. {/* validation */}
  343. {!vectorValueValid && (
  344. <Typography variant="caption" className={classes.error}>
  345. {searchTrans('vectorValueWarning', {
  346. dimension: selectedFieldDimension,
  347. })}
  348. </Typography>
  349. )}
  350. </fieldset>
  351. {/* collection and field selectors */}
  352. <fieldset className="field field-second">
  353. <Typography className="text">{searchTrans('secondTip')}</Typography>
  354. <CustomSelector
  355. options={collectionOptions}
  356. wrapperClass={classes.selector}
  357. variant="filled"
  358. label={searchTrans(
  359. collectionOptions.length === 0 ? 'noCollection' : 'collection'
  360. )}
  361. disabled={collectionOptions.length === 0}
  362. value={selectedCollection}
  363. onChange={(e: { target: { value: unknown } }) => {
  364. const collection = e.target.value;
  365. setSelectedCollection(collection as string);
  366. // every time selected collection changed, reset field
  367. setSelectedField('');
  368. }}
  369. />
  370. <CustomSelector
  371. options={fieldOptions}
  372. // readOnly can't avoid all events, so we use disabled instead
  373. disabled={selectedCollection === ''}
  374. wrapperClass={classes.selector}
  375. variant="filled"
  376. label={searchTrans('field')}
  377. value={selectedField}
  378. onChange={(e: { target: { value: unknown } }) => {
  379. const field = e.target.value;
  380. setSelectedField(field as string);
  381. }}
  382. />
  383. </fieldset>
  384. {/* search params selectors */}
  385. <fieldset className="field field-params">
  386. <Typography className="text">{searchTrans('thirdTip')}</Typography>
  387. <SearchParams
  388. wrapperClass={classes.paramsWrapper}
  389. metricType={metricType!}
  390. embeddingType={
  391. embeddingType as
  392. | DataTypeEnum.BinaryVector
  393. | DataTypeEnum.FloatVector
  394. }
  395. indexType={indexType}
  396. indexParams={indexParams!}
  397. searchParamsForm={searchParam}
  398. handleFormChange={setSearchParam}
  399. topK={topK}
  400. setParamsDisabled={setParamDisabled}
  401. />
  402. </fieldset>
  403. </form>
  404. {/**
  405. * search toolbar section
  406. * including topK selector, advanced filter, search and reset btn
  407. */}
  408. <section className={classes.toolbar}>
  409. <div className="left">
  410. <Typography variant="h5" className="text">
  411. {`${searchTrans('result')}: `}
  412. </Typography>
  413. {/* topK selector */}
  414. <SimpleMenu
  415. label={searchTrans('topK', { number: topK })}
  416. menuItems={TOP_K_OPTIONS.map(item => ({
  417. label: item.toString(),
  418. callback: () => {
  419. setTopK(item);
  420. if (!searchDisabled) {
  421. handleSearch(item);
  422. }
  423. },
  424. wrapperClass: classes.menuItem,
  425. }))}
  426. buttonProps={{
  427. className: classes.menuLabel,
  428. endIcon: <ArrowIcon />,
  429. }}
  430. menuItemWidth="108px"
  431. />
  432. <Filter
  433. title="Advanced Filter"
  434. fields={filterFields}
  435. filterDisabled={selectedField === '' || selectedCollection === ''}
  436. onSubmit={handleAdvancedFilterChange}
  437. />
  438. </div>
  439. <div className="right">
  440. <CustomButton className="btn" onClick={handleReset}>
  441. <ResetIcon classes={{ root: 'icon' }} />
  442. {btnTrans('reset')}
  443. </CustomButton>
  444. <CustomButton
  445. variant="contained"
  446. disabled={searchDisabled}
  447. onClick={() => handleSearch(topK)}
  448. >
  449. {btnTrans('search')}
  450. </CustomButton>
  451. </div>
  452. </section>
  453. {/* search result table section */}
  454. {(searchResult && searchResult.length > 0) || tableLoading ? (
  455. <MilvusGrid
  456. toolbarConfigs={[]}
  457. colDefinitions={colDefinitions}
  458. rows={result}
  459. rowCount={total}
  460. primaryKey="rank"
  461. page={currentPage}
  462. onChangePage={handlePageChange}
  463. rowsPerPage={pageSize}
  464. setRowsPerPage={handlePageSize}
  465. openCheckBox={false}
  466. isLoading={tableLoading}
  467. />
  468. ) : (
  469. <EmptyCard
  470. wrapperClass={`page-empty-card`}
  471. icon={<VectorSearchIcon />}
  472. text={
  473. searchResult !== null
  474. ? searchTrans('empty')
  475. : searchTrans('startTip')
  476. }
  477. />
  478. )}
  479. </section>
  480. );
  481. };
  482. export default VectorSearch;