Browse Source

update create index js and py template

tumao 3 years ago
parent
commit
54bc374f99

+ 6 - 2
client/src/components/code/CodeBlock.tsx

@@ -32,14 +32,18 @@ const CodeStyle = {
   fontSize: 14,
 };
 
-const CodeBlock: FC<CodeBlockProps> = ({ code, language }) => {
+const CodeBlock: FC<CodeBlockProps> = ({
+  code,
+  language,
+  wrapperClass = '',
+}) => {
   const classes = getStyles();
 
   const { t: commonTrans } = useTranslation();
   const copyTrans = commonTrans('copy', { returnObjects: true });
 
   return (
-    <div className={classes.wrapper}>
+    <div className={`${classes.wrapper} ${wrapperClass}`}>
       <CopyButton
         className={classes.copy}
         label={copyTrans.label}

+ 26 - 3
client/src/components/code/CodeView.tsx

@@ -66,15 +66,38 @@ const getStyles = makeStyles((theme: Theme) => ({
       borderBottom: 'none',
     },
   },
+
+  block: {
+    /**
+     * container height minus:
+     * 1. CodeView padding top and bottom (32 * 2)
+     * 2. CodeBlock padding top and bottom (24 * 2)
+     * 3. title height and margin bottom (24 + 16)
+     * 4. tab title height and margin bottom (36 + 16)
+     */
+    height: (props: { height: number }) =>
+      props.height - 32 * 2 - 24 * 2 - (24 + 16) - (36 + 16),
+    overflowY: 'auto',
+  },
 }));
 
-const CodeView: FC<CodeViewProps> = ({ wrapperClass = '', data }) => {
-  const classes = getStyles();
+const CodeView: FC<CodeViewProps> = ({
+  wrapperClass = '',
+  data,
+  height = 0,
+}) => {
+  const classes = getStyles({ height });
   const { t: commonTrans } = useTranslation();
 
   const tabs: ITab[] = data.map(item => ({
     label: item.label,
-    component: <CodeBlock language={item.language} code={item.code} />,
+    component: (
+      <CodeBlock
+        wrapperClass={height !== 0 ? classes.block : ''}
+        language={item.language}
+        code={item.code}
+      />
+    ),
   }));
 
   return (

+ 2 - 0
client/src/components/code/Types.ts

@@ -1,4 +1,5 @@
 export interface CodeViewProps {
+  height?: number;
   wrapperClass?: string;
   data: CodeViewData[];
 }
@@ -11,6 +12,7 @@ export enum CodeLanguageEnum {
 export interface CodeBlockProps {
   code: string;
   language: CodeLanguageEnum;
+  wrapperClass?: string;
 }
 
 export interface CodeViewData extends CodeBlockProps {

+ 21 - 3
client/src/components/customDialog/DialogTemplate.tsx

@@ -1,4 +1,4 @@
-import { FC } from 'react';
+import { FC, useEffect, useRef, useState } from 'react';
 import { useTranslation } from 'react-i18next';
 import {
   DialogContent,
@@ -61,9 +61,23 @@ const DialogTemplate: FC<DialogContainerProps> = ({
   const classes = useStyles({ showCode });
   const onCancel = handleCancel || handleClose;
 
+  const dialogRef = useRef(null);
+  const [dialogHeight, setDialogHeight] = useState<number>(0);
+
+  /**
+   * code mode height should not over original dialog height
+   * everytime children change, should recalculate dialog height
+   */
+  useEffect(() => {
+    if (dialogRef.current) {
+      const height = (dialogRef.current as any).offsetHeight;
+      setDialogHeight(height);
+    }
+  }, [children]);
+
   return (
     <section className={classes.wrapper}>
-      <div className={`${classes.dialog} ${classes.block}`}>
+      <div ref={dialogRef} className={`${classes.dialog} ${classes.block}`}>
         <CustomDialogTitle onClose={handleClose} showCloseIcon={showCloseIcon}>
           {title}
         </CustomDialogTitle>
@@ -93,7 +107,11 @@ const DialogTemplate: FC<DialogContainerProps> = ({
 
       <div className={`${classes.block} ${classes.codeWrapper}`}>
         {showCode && (
-          <CodeView wrapperClass={classes.code} data={codeBlocksData} />
+          <CodeView
+            height={dialogHeight}
+            wrapperClass={classes.code}
+            data={codeBlocksData}
+          />
         )}
       </div>
     </section>

+ 31 - 25
client/src/pages/schema/Create.tsx

@@ -10,7 +10,8 @@ import {
   METRIC_TYPES_VALUES,
 } from '../../consts/Milvus';
 import { useFormValidation } from '../../hooks/Form';
-import { getCreateIndexJSCode, getCreateIndexPYCode } from '../../utils/Code';
+import { getCreateIndexJSCode } from '../../utils/code/Js';
+import { getCreateIndexPYCode } from '../../utils/code/Py';
 import { formatForm, getMetricOptions } from '../../utils/Form';
 import { getEmbeddingType } from '../../utils/search';
 import { DataType } from '../collections/Types';
@@ -22,8 +23,12 @@ const CreateIndex = (props: {
   fieldType: DataType;
   handleCreate: (params: ParamPair[]) => void;
   handleCancel: () => void;
+
+  // used for code mode
+  fieldName: string;
 }) => {
-  const { collectionName, fieldType, handleCreate, handleCancel } = props;
+  const { collectionName, fieldType, handleCreate, handleCancel, fieldName } =
+    props;
 
   const { t: indexTrans } = useTranslation('index');
   const { t: dialogTrans } = useTranslation('dialog');
@@ -72,12 +77,30 @@ const CreateIndex = (props: {
     [indexSetting.index_type, fieldType]
   );
 
-  const indexParams = useMemo(() => {
+  const extraParams = useMemo(() => {
     const params: { [x: string]: string } = {};
     indexCreateParams.forEach(v => {
       params[v] = indexSetting[v];
     });
-    return params;
+
+    const { index_type, metric_type } = indexSetting;
+
+    const extraParams: ParamPair[] = [
+      {
+        key: 'index_type',
+        value: index_type,
+      },
+      {
+        key: 'metric_type',
+        value: metric_type,
+      },
+      {
+        key: 'params',
+        value: JSON.stringify(params),
+      },
+    ];
+
+    return extraParams;
   }, [indexCreateParams, indexSetting]);
 
   const indexOptions = useMemo(() => {
@@ -102,15 +125,15 @@ const CreateIndex = (props: {
       {
         label: commonTrans('js'),
         language: CodeLanguageEnum.javascript,
-        code: getCreateIndexJSCode(),
+        code: getCreateIndexJSCode({ collectionName, fieldName, extraParams }),
       },
       {
         label: commonTrans('py'),
         language: CodeLanguageEnum.python,
-        code: getCreateIndexPYCode(),
+        code: getCreateIndexPYCode({ collectionName, fieldName, extraParams }),
       },
     ],
-    [commonTrans]
+    [commonTrans, extraParams, collectionName, fieldName]
   );
 
   const { validation, checkIsValid, disabled, setDisabled, resetValidation } =
@@ -154,24 +177,7 @@ const CreateIndex = (props: {
   };
 
   const handleCreateIndex = () => {
-    const { index_type, metric_type } = indexSetting;
-
-    const params: ParamPair[] = [
-      {
-        key: 'index_type',
-        value: index_type,
-      },
-      {
-        key: 'metric_type',
-        value: metric_type,
-      },
-      {
-        key: 'params',
-        value: JSON.stringify(indexParams),
-      },
-    ];
-
-    handleCreate(params);
+    handleCreate(extraParams);
   };
 
   const handleShowCode = (event: React.ChangeEvent<{ checked: boolean }>) => {

+ 1 - 0
client/src/pages/schema/IndexTypeElement.tsx

@@ -173,6 +173,7 @@ const IndexTypeElement: FC<{
         component: (
           <CreateIndex
             collectionName={collectionName}
+            fieldName={data._fieldName}
             fieldType={data._fieldType}
             handleCancel={handleCloseDialog}
             handleCreate={requestCreateIndex}

+ 14 - 0
client/src/styles/common.css

@@ -61,3 +61,17 @@ fieldset {
 .dialog-content::first-letter {
   text-transform: uppercase;
 }
+
+/* change scrollbar style */
+::-webkit-scrollbar {
+  width: 8px;
+}
+
+::-webkit-scrollbar-track {
+  background-color: #f9f9f9;
+}
+
+::-webkit-scrollbar-thumb {
+  border-radius: 8px;
+  background-color: #eee;
+}

+ 0 - 27
client/src/utils/Code.ts

@@ -1,27 +0,0 @@
-export const getCreateIndexJSCode = () => {
-  const jsCode = `const a = 2;
-const testFunction = (input) => {
-  console.log(input)
-}
-testFunction(a)`;
-
-  return jsCode;
-};
-
-export const getCreateIndexPYCode = () => {
-  const pyCode = `# Python program to find the
-# maximum of two numbers
-  
-def maximum(a, b):
-  if a >= b:
-      return a
-  else:
-      return b
-      
-# Driver code
-a = 2
-b = 4
-print(maximum(a, b))`;
-
-  return pyCode;
-};

+ 14 - 0
client/src/utils/Format.ts

@@ -91,6 +91,20 @@ export const getKeyValuePairFromObj = (
   return pairs;
 };
 
+/**
+ * @param pairs e.g. [{key: 'key', value: 'value'}]
+ * @returns object, e.g. {key: value}
+ */
+export const getObjFromKeyValuePair = (
+  pairs: { key: string; value: any }[]
+): { [key in string]: any } => {
+  const obj = pairs.reduce((acc, cur) => {
+    acc[cur.key] = cur.value;
+    return acc;
+  }, {} as { [key in string]: any });
+  return obj;
+};
+
 export const getKeyValueListFromJsonString = (
   json: string
 ): { key: string; value: string }[] => {

+ 16 - 0
client/src/utils/code/Js.ts

@@ -0,0 +1,16 @@
+import { CreateIndexCodeParam } from './Types';
+
+export const getCreateIndexJSCode = (params: CreateIndexCodeParam) => {
+  const { collectionName, fieldName, extraParams } = params;
+
+  const jsCode = `import { MilvusClient } from '@zilliz/milvus2-sdk-node';
+const client = new MilvusClient(milvus_address)
+
+client.indexManager.createIndex({
+  collection_name: ${collectionName},
+  field_name: ${fieldName},
+  extra_params: ${JSON.stringify(extraParams, null, 2)},
+});`;
+
+  return jsCode;
+};

+ 27 - 0
client/src/utils/code/Py.ts

@@ -0,0 +1,27 @@
+import { getObjFromKeyValuePair } from '../Format';
+import { parseValue } from '../Insert';
+import { CreateIndexCodeParam } from './Types';
+
+// use replacer to parse extra param from JSON to original object
+const replacer = (key: string, value: any) => {
+  if (typeof value === 'string') {
+    return parseValue(value);
+  }
+  return value;
+};
+
+export const getCreateIndexPYCode = (params: CreateIndexCodeParam) => {
+  const { collectionName, fieldName, extraParams } = params;
+  const obj = getObjFromKeyValuePair(extraParams);
+  const index = {
+    ...obj,
+    params: parseValue(obj.params),
+  };
+  const pyCode = `from pymilvus_orm import Collection,
+
+collection = Collection('${collectionName}')
+index = ${JSON.stringify(index, replacer, 4)}
+collection.create_index(${fieldName}, index)`;
+
+  return pyCode;
+};

+ 10 - 0
client/src/utils/code/Types.ts

@@ -0,0 +1,10 @@
+export interface KeyValuePairs {
+  key: string;
+  value: string;
+}
+
+export interface CreateIndexCodeParam {
+  collectionName: string;
+  fieldName: string;
+  extraParams: KeyValuePairs[];
+}