id: example_code_node.md title: Run Milvus with Node.js label: Node.js order: 1 group: example_code.md

summary: Get started with Milvus faster using this Node.js example code.

{{tab}}

使用 Node.js 运行 Milvus

本主题介绍如何使用 Node.js 运行 Milvus。

1. 初始化 Node.js 项目

  1. npm init
要求 Node.js 12 或者更高版本。查看Node.js 初学者指南获取有关如何在你的系统上安装正确版本的信息。

2. 安装 TypeScript 和 Node Milvus SDK 及其依赖

  1. npm install @zilliz/milvus2-sdk-node typescript --save

3. 下载示例代码 HelloMilvus.ts

  1. $ wget https://raw.githubusercontent.com/milvus-io/milvus-sdk-node/main/example/HelloMilvus.ts

4. HelloMilvus.ts 代码详解

此示例代码将执行以下操作:

  • 导入 Node.js SDK 包:

    1. import { MilvusClient } from "@zilliz/milvus2-sdk-node"
    2. import { DataType } from "@zilliz/milvus2-sdk-node/dist/milvus/types/Common";
    3. import { InsertReq } from "@zilliz/milvus2-sdk-node/dist/milvus/types/Insert";
  • 连接服务器:

    1. const milvusClient = new MilvusClient("localhost:19530");
    2. const collectionManager = milvusClient.collectionManager;
  • 创建一个 collection: ```ts const collectionName = “hello_milvus”; const dim = “4”; const createRes = await collectionManager.createCollection(

    1. {
    2. collection_name: collectionName,
    3. fields: [
    4. {
    5. name: "count",
    6. data_type: DataType.Int64,
    7. is_primary_key: true,
    8. description: "",
    9. },
    10. {
    11. name: "random_value",
    12. data_type: DataType.Double,
    13. description: "",
    14. },
    15. {
    16. name: "float_vector",
    17. data_type: DataType.FloatVector,
    18. description: "",
    19. type_params: {
    20. dim
    21. }
    22. }
    23. ]
    24. }

    );

  1. console.log("--- Create collection ---", createRes, collectionName);
  1. - 在创建好的 collection 中插入向量:
  2. ```ts
  3. const generateInsertData = function generateInsertData(
  4. fields: { isVector: boolean; dim?: number; name: string; isBool?: boolean }[],
  5. count: number) {
  6. const results = [];
  7. while (count > 0) {
  8. let value: any = {};
  9. fields.forEach((v) => {
  10. const { isVector, dim, name, isBool } = v;
  11. value[name] = isVector
  12. ? [...Array(dim)].map(() => Math.random() * 10)
  13. : isBool
  14. ? count % 2 === 0
  15. : count;
  16. });
  17. value["count"] = count;
  18. results.push(value);
  19. count--;
  20. }
  21. return results;
  22. }
  23. const fields = [
  24. {
  25. isVector: true,
  26. dim: 4,
  27. name: "float_vector",
  28. },
  29. {
  30. isVector: false,
  31. name: "random_value",
  32. },
  33. ];
  34. const vectorsData = generateInsertData(fields, 1000);
  35. const params: InsertReq = {
  36. collection_name: collectionName,
  37. fields_data: vectorsData,
  38. partition_name: "test",
  39. };
  40. await milvusClient.dataManager.insert(params);
  41. console.log("--- Insert Data to Collection ---");
  • 将 collection 加载到内存并构建索引:

    1. await milvusClient.indexManager.createIndex({
    2. collection_name: collectionName,
    3. field_name: "float_vector",
    4. extra_params: {
    5. index_type: "IVF_FLAT",
    6. metric_type: "L2",
    7. params: JSON.stringify({ nlist: 10 }),
    8. },
    9. });
    10. console.log("--- Create Index in Collection ---");
  • 在 collection 中执行搜索操作 ```ts

    1. // need load collection before search

    const loadCollectionRes = await collectionManager.loadCollectionSync({

    1. collection_name: collectionName,

    }); console.log(“—- Load collection (“ + collectionName + “) —-“, loadCollectionRes);

  1. const result = await milvusClient.dataManager.search({
  2. collection_name: collectionName,
  3. vectors: [vectorsData[0]["float_vector"]],
  4. search_params: {
  5. anns_field: "float_vector",
  6. topk: "4",
  7. metric_type: "L2",
  8. params: JSON.stringify({ nprobe: 1024 }),
  9. round_decimal: 4,
  10. },
  11. output_fields: ["count"],
  12. vector_type: DataType.FloatVector,
  13. });
  14. console.log("--- Search collection (" + collectionName + ") ---", result);
  1. - 从内存中释放 collection
  2. ```ts
  3. const releaseRes = await collectionManager.releaseCollection({
  4. collection_name: collectionName,
  5. });
  6. console.log("--- Release Collection ---", releaseRes);
  • 删除 collection:
    1. const dropRes = await collectionManager.dropCollection({
    2. collection_name: collectionName,
    3. });
    4. console.log("--- Drop Collection ---", dropRes);

5. 编译文件

  1. tsc MilvusHello.ts

6. 运行示例代码

  1. node MilvusHello.ts


恭喜!你已成功启动了 Milvus 单机版并创建了你的第一个 collection。