VectorSearch.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. // only non vector type fields can be advanced filter
  206. const filterFields = getNonVectorFieldsForFilter(nonVectorFields);
  207. setFilterFields(filterFields);
  208. },
  209. []
  210. );
  211. useEffect(() => {
  212. fetchCollections();
  213. }, [fetchCollections]);
  214. // get field options with index when selected collection changed
  215. useEffect(() => {
  216. if (selectedCollection !== '') {
  217. fetchFieldsWithIndex(selectedCollection, collections);
  218. }
  219. }, [selectedCollection, collections, fetchFieldsWithIndex]);
  220. // set default collection value if is from overview page
  221. useEffect(() => {
  222. if (location.search && collections.length > 0) {
  223. const { collectionName } = parseLocationSearch(location.search);
  224. // collection name validation
  225. const isNameValid = collections
  226. .map(c => c._name)
  227. .includes(collectionName);
  228. isNameValid && setSelectedCollection(collectionName);
  229. }
  230. }, [location, collections]);
  231. // icons
  232. const VectorSearchIcon = icons.vectorSearch;
  233. const ResetIcon = icons.refresh;
  234. const ArrowIcon = icons.dropdown;
  235. // methods
  236. const handlePageChange = (e: any, page: number) => {
  237. handleCurrentPage(page);
  238. };
  239. const handleReset = () => {
  240. /**
  241. * reset search includes:
  242. * 1. reset vectors
  243. * 2. reset selected collection and field
  244. * 3. reset search params
  245. * 4. reset advanced filter expression
  246. * 5. clear search result
  247. */
  248. setVectors('');
  249. setSelectedField('');
  250. setSelectedCollection('');
  251. setSearchResult(null);
  252. setFilterFields([]);
  253. setExpression('');
  254. };
  255. const handleSearch = async (topK: number, expr = expression) => {
  256. const searhParamPairs = [
  257. // dynamic search params
  258. {
  259. key: 'params',
  260. value: JSON.stringify(searchParam),
  261. },
  262. {
  263. key: 'anns_field',
  264. value: selectedField,
  265. },
  266. {
  267. key: 'topk',
  268. value: topK,
  269. },
  270. {
  271. key: 'metric_type',
  272. value: metricType,
  273. },
  274. ];
  275. const params: VectorSearchParam = {
  276. output_fields: outputFields,
  277. expr,
  278. search_params: searhParamPairs,
  279. vectors: [parseValue(vectors)],
  280. vector_type: fieldType,
  281. };
  282. setTableLoading(true);
  283. try {
  284. const res = await CollectionHttp.vectorSearchData(
  285. selectedCollection,
  286. params
  287. );
  288. setTableLoading(false);
  289. const result = transferSearchResult(res.results);
  290. setSearchResult(result);
  291. } catch (err) {
  292. setTableLoading(false);
  293. }
  294. };
  295. const handleAdvancedFilterChange = (expression: string) => {
  296. setExpression(expression);
  297. if (!searchDisabled) {
  298. handleSearch(topK, expression);
  299. }
  300. };
  301. const handleVectorChange = (value: string) => {
  302. setVectors(value);
  303. };
  304. return (
  305. <section className="page-wrapper">
  306. {/* form section */}
  307. <form className={classes.form}>
  308. {/**
  309. * vector value textarea
  310. * use field-params class because it also has error msg if invalid
  311. */}
  312. <fieldset className="field field-params">
  313. <Typography className="text">
  314. {searchTrans('firstTip', {
  315. dimensionTip:
  316. selectedFieldDimension !== 0
  317. ? `(dimension: ${selectedFieldDimension})`
  318. : '',
  319. })}
  320. </Typography>
  321. <TextField
  322. className="textarea"
  323. InputProps={{
  324. classes: {
  325. root: 'textfield',
  326. multiline: 'multiline',
  327. },
  328. }}
  329. multiline
  330. rows={5}
  331. placeholder={searchTrans('vectorPlaceholder')}
  332. value={vectors}
  333. onChange={(e: React.ChangeEvent<{ value: unknown }>) => {
  334. handleVectorChange(e.target.value as string);
  335. }}
  336. />
  337. {/* validation */}
  338. {!vectorValueValid && (
  339. <Typography variant="caption" className={classes.error}>
  340. {searchTrans('vectorValueWarning', {
  341. dimension: selectedFieldDimension,
  342. })}
  343. </Typography>
  344. )}
  345. </fieldset>
  346. {/* collection and field selectors */}
  347. <fieldset className="field field-second">
  348. <Typography className="text">{searchTrans('secondTip')}</Typography>
  349. <CustomSelector
  350. options={collectionOptions}
  351. wrapperClass={classes.selector}
  352. variant="filled"
  353. label={searchTrans(
  354. collectionOptions.length === 0 ? 'noCollection' : 'collection'
  355. )}
  356. disabled={collectionOptions.length === 0}
  357. value={selectedCollection}
  358. onChange={(e: { target: { value: unknown } }) => {
  359. const collection = e.target.value;
  360. setSelectedCollection(collection as string);
  361. // every time selected collection changed, reset field
  362. setSelectedField('');
  363. }}
  364. />
  365. <CustomSelector
  366. options={fieldOptions}
  367. // readOnly can't avoid all events, so we use disabled instead
  368. disabled={selectedCollection === ''}
  369. wrapperClass={classes.selector}
  370. variant="filled"
  371. label={searchTrans('field')}
  372. value={selectedField}
  373. onChange={(e: { target: { value: unknown } }) => {
  374. const field = e.target.value;
  375. setSelectedField(field as string);
  376. }}
  377. />
  378. </fieldset>
  379. {/* search params selectors */}
  380. <fieldset className="field field-params">
  381. <Typography className="text">{searchTrans('thirdTip')}</Typography>
  382. <SearchParams
  383. wrapperClass={classes.paramsWrapper}
  384. metricType={metricType!}
  385. embeddingType={
  386. embeddingType as
  387. | DataTypeEnum.BinaryVector
  388. | DataTypeEnum.FloatVector
  389. }
  390. indexType={indexType}
  391. indexParams={indexParams!}
  392. searchParamsForm={searchParam}
  393. handleFormChange={setSearchParam}
  394. topK={topK}
  395. setParamsDisabled={setParamDisabled}
  396. />
  397. </fieldset>
  398. </form>
  399. {/**
  400. * search toolbar section
  401. * including topK selector, advanced filter, search and reset btn
  402. */}
  403. <section className={classes.toolbar}>
  404. <div className="left">
  405. <Typography variant="h5" className="text">
  406. {`${searchTrans('result')}: `}
  407. </Typography>
  408. {/* topK selector */}
  409. <SimpleMenu
  410. label={searchTrans('topK', { number: topK })}
  411. menuItems={TOP_K_OPTIONS.map(item => ({
  412. label: item.toString(),
  413. callback: () => {
  414. setTopK(item);
  415. if (!searchDisabled) {
  416. handleSearch(item);
  417. }
  418. },
  419. wrapperClass: classes.menuItem,
  420. }))}
  421. buttonProps={{
  422. className: classes.menuLabel,
  423. endIcon: <ArrowIcon />,
  424. }}
  425. menuItemWidth="108px"
  426. />
  427. <Filter
  428. title="Advanced Filter"
  429. fields={filterFields}
  430. filterDisabled={selectedField === '' || selectedCollection === ''}
  431. onSubmit={handleAdvancedFilterChange}
  432. />
  433. </div>
  434. <div className="right">
  435. <CustomButton className="btn" onClick={handleReset}>
  436. <ResetIcon classes={{ root: 'icon' }} />
  437. {btnTrans('reset')}
  438. </CustomButton>
  439. <CustomButton
  440. variant="contained"
  441. disabled={searchDisabled}
  442. onClick={() => handleSearch(topK)}
  443. >
  444. {btnTrans('search')}
  445. </CustomButton>
  446. </div>
  447. </section>
  448. {/* search result table section */}
  449. {(searchResult && searchResult.length > 0) || tableLoading ? (
  450. <MilvusGrid
  451. toolbarConfigs={[]}
  452. colDefinitions={colDefinitions}
  453. rows={result}
  454. rowCount={total}
  455. primaryKey="rank"
  456. page={currentPage}
  457. onChangePage={handlePageChange}
  458. rowsPerPage={pageSize}
  459. setRowsPerPage={handlePageSize}
  460. openCheckBox={false}
  461. isLoading={tableLoading}
  462. />
  463. ) : (
  464. <EmptyCard
  465. wrapperClass={`page-empty-card`}
  466. icon={<VectorSearchIcon />}
  467. text={
  468. searchResult !== null
  469. ? searchTrans('empty')
  470. : searchTrans('startTip')
  471. }
  472. />
  473. )}
  474. </section>
  475. );
  476. };
  477. export default VectorSearch;