✦ Puxiaoshuai · Time is a river painted on scrolls · Walk to the water’s end, sit and watch the clouds rise

milvus2026.08.27 · 8 min read

milvus简易增删改查

milvus增删改查

L

Leo

2026.08.27 · Updated 2026.09.13

4 views
milvus简易增删改查

insert.js 存储流程(Mermaid 图)

流程要点

  1. 前置准备:从 .env 读配置 → 初始化嵌入模型 → 创建 Milvus 客户端。
  2. 建集合:定义 6 个字段,其中 vector 必须是 1024 维,与嵌入模型输出一致。
  3. 建索引:对 vector 字段建 IVF_FLAT + 余弦相似度索引,这是向量搜索能快的前提。
  4. 加载集合:Milvus 是「先加载后查询」模式,加载后才能搜索。
  5. 生成向量 + 插入:Promise.all 并发把每条 content 文本转成向量,然后 insert 批量写入。

Milvus 增删改查总结(src/ 下 4 个核心方法)

操作对应文件SDK 方法SQL 类比
增 Createinsert.jsclient.insert()INSERT INTO
删 Deletedelete.jsclient.delete()DELETE ... WHERE
改 Updateupdate.jsclient.upsert()UPDATE ... SET(实际是"按主键覆盖")
查 Readquery.js / rag.jsclient.search()SELECT ... ORDER BY 相似度

增 —— client.insert()(insert.js)

await client.insert({ collection_name: COLLECTION_NAME, data: diaryData });

前提:先 createCollection 建集合 → createIndex 建向量索引 → loadCollection 加载。插入前要把文本用 embedding 模型转成向量。

删 —— client.delete()(delete.js)

await client.delete({
    collection_name: COLLECTION_NAME,
    filter: `id == "diary_005"`                    // 删单条
    // filter: `id in ["diary_002", "diary_003"]`  // 批量删
    // filter: `mood == "sad"`                     // 条件删
});

filter 是类 SQL 的布尔表达式,等价于 WHERE 子句,灵活度很高。

改 —— client.upsert()(update.js)

const vector = await getEmbedding(updatedContent.content);   // 内容变了,向量必须重算
const updateData = { ...updatedContent, vector };
await client.upsert({ collection_name: COLLECTION_NAME, data: [updateData] });

Milvus 没有 update 方法,更新靠 upsert(按主键 id 判断:存在就覆盖、不存在就插入)。关键点:改了内容必须同步重算 embedding,否则向量检索仍按旧语义匹配。

查 —— client.search()(query.js / rag.js)

const queryVector = await getEmbedding(query);     // 先给"问题文本"转向量
const searchResult = await client.search({
    collection_name: COLLECTION_NAME,
    vector: queryVector,                           // 用向量找向量
    limit: 2,                                      // 返回 top-2
    metric_type: MetricType.COSINE,                // 相似度度量
    output_fields: ['id', 'content', 'date', 'mood', 'tags']  // 要返回的字段
});

查是 Milvus 的核心特色:把问题也转成向量,去库里找"最像的 top-k 条",每条带 score(相似度分数)。

rag.js 是"查"的进阶用法:search 检索出相关日记 → 拼成上下文 → 丢给 LLM 生成回答(RAG 全流程)。

一句话总结

增用 insert,删用 delete(filter 过滤),改用 upsert(没有 update),查用 search(向量相似度)。前三个都像普通数据库,唯独查彻底不一样——永远在"找最相似的向量",所以增删改都绕不开向量这个字段。

Tagsmilvus
L

Leo

Blogger

Independent developer / Blogger and the maintainer of the original blog “大道至简”. Migrating years of posts and shiyu from WordPress to Next.js.

Reader comments

COMMENTS · 0

Leave a comment

Comments are shown after moderation · be kind0/100