CreateIndex API执行流程_milvus源码解析

简介: CreateIndex API执行流程_milvus源码解析

CreateIndex API执行流程源码解析

milvus版本:v2.3.2

整体架构:

architecture.png

CreateIndex 的数据流向:

create_index数据流向.jpg

1.客户端sdk发出CreateIndex API请求。

import numpy as np
from pymilvus import (
    connections,
    FieldSchema, CollectionSchema, DataType,
    Collection,
)

num_entities, dim = 2000, 8


print("start connecting to Milvus")
connections.connect("default", host="192.168.230.71", port="19530")


fields = [
    FieldSchema(name="pk", dtype=DataType.VARCHAR, is_primary=True, auto_id=False, max_length=100),
    FieldSchema(name="random", dtype=DataType.DOUBLE),
    FieldSchema(name="embeddings", dtype=DataType.FLOAT_VECTOR, dim=dim)
]

schema = CollectionSchema(fields, "hello_milvus is the simplest demo to introduce the APIs")

print("Create collection `hello_milvus`")
hello_milvus = Collection("hello_milvus", schema, consistency_level="Strong")


print("Start inserting entities")
rng = np.random.default_rng(seed=19530)
entities = [
    # provide the pk field because `auto_id` is set to False
    [str(i) for i in range(num_entities)],
    rng.random(num_entities).tolist(),  # field random, only supports list
    rng.random((num_entities, dim)),    # field embeddings, supports numpy.ndarray and list
]

insert_result = hello_milvus.insert(entities)

hello_milvus.flush()

print("Start Creating index IVF_FLAT")
index = {
   
   
    "index_type": "IVF_FLAT",
    "metric_type": "L2",
    "params": {
   
   "nlist": 8},
}

hello_milvus.create_index("embeddings", index,index_name="idx_embeddings")

客户端SDK向proxy发送一个CreateIndex API请求,在embeddings列上创建一个名为idx_embeddings的索引。

2.客户端接受API请求,将request封装为createIndexTask,并压入ddQueue队列。

代码路径:internal\proxy\impl.go

// CreateIndex create index for collection.
func (node *Proxy) CreateIndex(ctx context.Context, request *milvuspb.CreateIndexRequest) (*commonpb.Status, error) {
   
   
    ......

    // request封装为task
    cit := &createIndexTask{
   
   
        ctx:                ctx,
        Condition:          NewTaskCondition(ctx),
        req:                request,
        rootCoord:          node.rootCoord,
        datacoord:          node.dataCoord,
        replicateMsgStream: node.replicateMsgStream,
    }

    ......
    // 将task压入ddQueue队列

    if err := node.sched.ddQueue.Enqueue(cit); err != nil {
   
   
        ......
    }

    ......
    // 等待cct执行完
    if err := cit.WaitToFinish(); err != nil {
   
   
        ......
    }

    ......
}

3.执行createIndexTask的3个方法PreExecute、Execute、PostExecute。

PreExecute()一般为参数校验等工作。

Execute()一般为真正执行逻辑。

代码路径:internal\proxy\task_index.go

func (cit *createIndexTask) Execute(ctx context.Context) error {
   
   
    ......
    req := &indexpb.CreateIndexRequest{
   
   
        CollectionID:    cit.collectionID,
        FieldID:         cit.fieldSchema.GetFieldID(),
        IndexName:       cit.req.GetIndexName(),
        TypeParams:      cit.newTypeParams,
        IndexParams:     cit.newIndexParams,
        IsAutoIndex:     cit.isAutoIndex,
        UserIndexParams: cit.newExtraParams,
        Timestamp:       cit.BeginTs(),
    }
    cit.result, err = cit.datacoord.CreateIndex(ctx, req)
    ......
    SendReplicateMessagePack(ctx, cit.replicateMsgStream, cit.req)
    return nil
}

从代码可以看出调用了datacoord的CreateIndex接口。

4.进入datacoord的CreateIndex接口。

代码路径:internal\datacoord\index_service.go

// CreateIndex create an index on collection.
// Index building is asynchronous, so when an index building request comes, an IndexID is assigned to the task and
// will get all flushed segments from DataCoord and record tasks with these segments. The background process
// indexBuilder will find this task and assign it to IndexNode for execution.
func (s *Server) CreateIndex(ctx context.Context, req *indexpb.CreateIndexRequest) (*commonpb.Status, error) {
   
   
    ......
    // 分配indexID,indexID=0
    indexID, err := s.meta.CanCreateIndex(req)
    ......

    if indexID == 0 {
   
   
        // 分配indexID
        indexID, err = s.allocator.allocID(ctx)
        ......
    }

    index := &model.Index{
   
   
        CollectionID:    req.GetCollectionID(),
        FieldID:         req.GetFieldID(),
        IndexID:         indexID,
        IndexName:       req.GetIndexName(),
        TypeParams:      req.GetTypeParams(),
        IndexParams:     req.GetIndexParams(),
        CreateTime:      req.GetTimestamp(),
        IsAutoIndex:     req.GetIsAutoIndex(),
        UserIndexParams: req.GetUserIndexParams(),
    }

    // Get flushed segments and create index

    err = s.meta.CreateIndex(index)
    ......

    // 将collectionID发送到channel,其它的goroutine进行消费。
    select {
   
   
    case s.notifyIndexChan <- req.GetCollectionID():
    default:
    }

    ......
}

变量index:

index_model.jpg

5.进入s.meta.CreateIndex()

代码路径:internal\datacoord\index_meta.go

func (m *meta) CreateIndex(index *model.Index) error {
   
   
    ......
    // 写入etcd元数据
    if err := m.catalog.CreateIndex(m.ctx, index); err != nil {
   
   
        ......
    }

    m.updateCollectionIndex(index)
    ......
}

在这里重点研究m.catalog.CreateIndex()这个方法做了什么事情。

func (kc *Catalog) CreateIndex(ctx context.Context, index *model.Index) error {
   
   
    key := BuildIndexKey(index.CollectionID, index.IndexID)

    value, err := proto.Marshal(model.MarshalIndexModel(index))
    if err != nil {
   
   
        return err
    }

    err = kc.MetaKv.Save(key, string(value))
    if err != nil {
   
   
        return err
    }
    return nil
}

在etcd会产生1个key。

==field-index/445834678636119060/445834678636519085==

value的值的结构为indexpb.FieldIndex,然后进行protobuf序列化后存入etcd。

因此etcd存储的是二进制数据。

&indexpb.FieldIndex{
   
   
    IndexInfo: &indexpb.IndexInfo{
   
   
        CollectionID:    index.CollectionID,
        FieldID:         index.FieldID,
        IndexName:       index.IndexName,
        IndexID:         index.IndexID,
        TypeParams:      index.TypeParams,
        IndexParams:     index.IndexParams,
        IsAutoIndex:     index.IsAutoIndex,
        UserIndexParams: index.UserIndexParams,
    },
    Deleted:    index.IsDeleted,
    CreateTime: index.CreateTime,
}

fieldindex.jpg

跟踪BuildIndexKey()函数,即可以得到key的规则。整理如下:

key规则:

  • 前缀/field-index/{collectionID}/{IndexID}

可以反映index属于哪个collection。Index的value可以反映属于哪个field。

不能反映属于哪个partition、哪个segment。

总结:

  • CreateIndex由proxy传递给协调器dataCoord操作etcd。
  • CreateIndex最终会在etcd上写入1种类型的key(其实还有一种,在另一篇中进行介绍)。
目录
相关文章
|
4天前
|
Java Android开发
Android12 双击power键启动相机源码解析
Android12 双击power键启动相机源码解析
13 0
|
1天前
PandasTA 源码解析(一)(2)
PandasTA 源码解析(一)
7 0
|
2天前
|
算法 Linux 调度
xenomai内核解析--xenomai与普通linux进程之间通讯XDDP(一)--实时端socket创建流程
xenomai与普通linux进程之间通讯XDDP(一)--实时端socket创建流程
6 1
xenomai内核解析--xenomai与普通linux进程之间通讯XDDP(一)--实时端socket创建流程
|
2天前
|
Linux 调度 数据库
|
2天前
|
Linux API 调度
xenomai内核解析-xenomai实时线程创建流程
本文介绍了linux硬实时操作系统xenomai pthread_creta()接口的底层实现原理,解释了如何在双内核间创建和调度一个xenomai任务。本文是基于源代码的分析,提供了详细的流程和注释,同时给出了结论部分,方便读者快速了解核心内容。
6 0
xenomai内核解析-xenomai实时线程创建流程
|
3天前
|
供应链 监控 安全
全面剖析:新页ERP系统不为人知的一面,以及系统的工作流程解析!
全面剖析:新页ERP系统不为人知的一面,以及系统的工作流程解析!
|
4天前
|
供应链 搜索推荐 API
API在电子商务中的应用与优势:深入解析
API是电子商务成功的关键,它们不仅促进了技术创新,还提高了用户体验和运营效率。随着技术的不断进步,API将继续在电子商务领域发挥更加重要的作用。电子商务平台通过利用API,可以更加灵活地适应市场变化,提供更加丰富和个性化的购物体验,最终实现业务的增长和扩展。
|
4天前
|
分布式计算 Java API
Java8 Lambda实现源码解析
Java8的lambda应该大家都比较熟悉了,本文主要从源码层面探讨一下lambda的设计和实现。
|
5天前
|
算法 Java Go
ArrayList源码解析
ArrayList源码解析
10 1
|
5天前
|
存储 安全 Java
【HashMap源码解析(一)(佬你不来看看?)】
【HashMap源码解析(一)(佬你不来看看?)】
11 1

推荐镜像

更多