Загрузка и освобождение

Загрузка коллекции является обязательным условием для проведения поиска по схожести и выполнения запросов в коллекциях. На этой странице рассматриваются процедуры загрузки и освобождения коллекции.

Предварительные условия

Перед загрузкой коллекции убедитесь в следующем:

  • Вы проиндексировали как минимум все векторные поля и, по желанию, некоторые скалярные поля.

Загрузка коллекции

При загрузке коллекции Milvus загружает в память индексные файлы и исходные данные всех полей для быстрого отклика на поиски и запросы. Элементы, вставленные после загрузки коллекции, автоматически индексируются и загружаются.

Следующие фрагменты кода демонстрируют, как загрузить коллекцию.

from pymilvus import MilvusClient

client = MilvusClient(
    uri="http://localhost:19530",
    token="root:Milvus"
)

# 7. Load the collection
client.load_collection(
    collection_name="my_collection"
)

res = client.get_load_state(
    collection_name="my_collection"
)

print(res)

# Output
#
# {
#     "state": "<LoadState: Loaded>"
# }
import io.milvus.v2.service.collection.request.LoadCollectionReq;
import io.milvus.v2.service.collection.request.GetLoadStateReq;
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;

String CLUSTER_ENDPOINT = "http://localhost:19530";
String TOKEN = "root:Milvus";

// 1. Connect to Milvus
ConnectConfig connectConfig = ConnectConfig.builder()
        .uri(CLUSTER_ENDPOINT)
        .token(TOKEN)
        .build();

MilvusClientV2 client = new MilvusClientV2(connectConfig);

// 7. Load the collection
LoadCollectionReq loadCollectionReq = LoadCollectionReq.builder()
        .collectionName("my_collection")
        .build();

client.loadCollection(loadCollectionReq);

// Get load state of the collection
GetLoadStateReq loadStateReq = GetLoadStateReq.builder()
        .collectionName("my_collection")
        .build();

Boolean res = client.getLoadState(loadStateReq);
System.out.println(res);

// Output:
// true
import (
    "context"
    "fmt"

    "github.com/milvus-io/milvus/client/v3/milvusclient"
)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

milvusAddr := "http://localhost:19530"
token := "root:Milvus"

client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
    Address: milvusAddr,
    APIKey:  token,
})
if err != nil {
    fmt.Println(err.Error())
    // handle error
}
defer client.Close(ctx)

loadTask, err := client.LoadCollection(ctx, milvusclient.NewLoadCollectionOption("my_collection"))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

// sync wait collection to be loaded
err = loadTask.Await(ctx)
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

state, err := client.GetLoadState(ctx, milvusclient.NewGetLoadStateOption("my_collection"))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}
fmt.Println(state.State)
use milvus::v2::prelude::*;

let client = ClientV2::new(
    &ConnectConfig::new()
        .uri("http://localhost:19530")
        .token("root:Milvus"),
)
.await?;

// 7. Load the collection
client
    .load_collection(
        LoadCollectionRequest::builder()
            .collection_name("my_collection")
            .build()?,
    )
    .await?;

let res = client
    .get_load_state(
        GetLoadStateRequest::builder()
            .collection_name("my_collection")
            .build()?,
    )
    .await?;

println!("{:?}", res.state());
#include <iostream>

#include "milvus/MilvusClientV2.h"

auto client = milvus::MilvusClientV2::Create();

milvus::ConnectParam connect_param{"http://localhost:19530", "root:Milvus"};
auto status = client->Connect(connect_param);
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}

status = client->LoadCollection(milvus::LoadCollectionRequest()
                                    .WithCollectionName("my_collection"));
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}

milvus::GetLoadStateResponse response;
status = client->GetLoadState(milvus::GetLoadStateRequest()
                                  .WithCollectionName("my_collection"),
                              response);
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}
std::cout << std::to_string(response.State()) << std::endl;
import { MilvusClient } from "@zilliz/milvus2-sdk-node";

const address = "http://localhost:19530";
const token = "root:Milvus";
const client = new MilvusClient({address, token});

// 7. Load the collection
let res = await client.loadCollection({
    collection_name: "my_collection"
})

console.log(res.error_code)

// Output
//
// Success
//

res = await client.getLoadState({
    collection_name: "my_collection"
})

console.log(res.state)

// Output
//
// LoadStateLoaded
//
using Milvus.Client.V2;
using Milvus.Client.V2.Requests.Collection;
using Milvus.Client.V2.Responses.Collection;
using Milvus.Client.V2.Types;

const string CLUSTER_ENDPOINT = "http://localhost:19530";

using var client = new MilvusClientV2(new ConnectConfig
{
    Uri = CLUSTER_ENDPOINT,
    ApiKey = "root:Milvus"
});
await client.ConnectAsync();

// 7. Load the collection
await client.LoadCollectionAsync(new LoadCollectionReq
{
    CollectionName = "my_collection"
});

// Get load state of the collection
GetLoadStateResp res = await client.GetLoadStateAsync(new GetLoadStateReq
{
    CollectionName = "my_collection"
});
Console.WriteLine(res.State);
export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/load" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--header "Request-Timeout: 10" \
-d '{
    "collectionName": "my_collection"
}'

# {
#     "code": 0,
#     "data": {}
# }

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/get_load_state" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--header "Request-Timeout: 10" \
-d '{
    "collectionName": "my_collection"
}'

# {
#     "code": 0,
#     "data": {
#         "loadProgress": 100,
#         "loadState": "LoadStateLoaded",
#         "message": ""
#     }
# }

Загрузка определённых полей

Milvus может загружать только те поля, которые участвуют в поисках и запросах, что позволяет снизить потребление памяти и повысить производительность поиска.

Частичная загрузка коллекции в настоящее время находится в бета-версии и не рекомендуется для использования в производственной среде.

В следующем фрагменте кода предполагается, что вы создали коллекцию с именем my_collection, и в ней есть два поля: my_id и my_vector.

client.load_collection(
    collection_name="my_collection",
    load_fields=["my_id", "my_vector"], # Load only the specified fields
    skip_load_dynamic_field=True # Skip loading the dynamic field
)

res = client.get_load_state(
    collection_name="my_collection"
)

print(res)

# Output
#
# {
#     "state": "<LoadState: Loaded>"
# }
import io.milvus.v2.service.collection.request.GetLoadStateReq;
import io.milvus.v2.service.collection.request.LoadCollectionReq;
import java.util.Arrays;

// Load the collection
LoadCollectionReq loadCollectionReq = LoadCollectionReq.builder()
        .collectionName("my_collection")
        .loadFields(Arrays.asList("my_id", "my_vector"))
        .skipLoadDynamicField(true)
        .build();

client.loadCollection(loadCollectionReq);

// Get load state of the collection
GetLoadStateReq loadStateReq = GetLoadStateReq.builder()
        .collectionName("my_collection")
        .build();

Boolean res = client.getLoadState(loadStateReq);
System.out.println(res);
import (
    "fmt"

    "github.com/milvus-io/milvus/client/v3/milvusclient"
)

loadTask, err := client.LoadCollection(ctx, milvusclient.NewLoadCollectionOption("my_collection").
    WithLoadFields("my_id", "my_vector").
    WithSkipLoadDynamicField(true))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

// sync wait collection to be loaded
err = loadTask.Await(ctx)
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

state, err := client.GetLoadState(ctx, milvusclient.NewGetLoadStateOption("my_collection"))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}
fmt.Println(state.State)
use milvus::v2::prelude::*;

client
    .load_collection(
        LoadCollectionRequest::builder()
            .collection_name("my_collection")
            .load_fields(["my_id", "my_vector"])
            .skip_load_dynamic_field(true)
            .build()?,
    )
    .await?;

let res = client
    .get_load_state(
        GetLoadStateRequest::builder()
            .collection_name("my_collection")
            .build()?,
    )
    .await?;

println!("{:?}", res.state());
auto status = client->LoadCollection(milvus::LoadCollectionRequest()
                                        .WithCollectionName("my_collection")
                                        .AddLoadField("my_id")
                                        .AddLoadField("my_vector")
                                        .WithSkipDynamicField(true));
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}

milvus::GetLoadStateResponse response;
status = client->GetLoadState(milvus::GetLoadStateRequest()
                                  .WithCollectionName("my_collection"),
                              response);
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}
std::cout << std::to_string(response.State()) << std::endl;
await client.loadCollection({
  collection_name: "my_collection",
  load_fields: ["my_id", "my_vector"], // Load only the specified fields
  skip_load_dynamic_field: true // Skip loading the dynamic field
});

const res = await client.getLoadState({
    collection_name: "my_collection",
});

console.log(res.state);

// Output
//
// LoadStateLoaded
using Milvus.Client.V2.Requests.Collection;
using Milvus.Client.V2.Responses.Collection;
using Milvus.Client.V2.Types;

// Load the collection
await client.LoadCollectionAsync(new LoadCollectionReq
{
    CollectionName = "my_collection",
    LoadFields = new[] { "my_id", "my_vector" }, // Load only the specified fields
    SkipLoadDynamicField = true // Skip loading the dynamic field
});

// Get load state of the collection
GetLoadStateResp res = await client.GetLoadStateAsync(new GetLoadStateReq
{
    CollectionName = "my_collection"
});
Console.WriteLine(res.State);
# The RESTful API does not expose partial collection loading.

Если вы решите загружать определенные поля, стоит отметить, что в качестве фильтров и полей вывода в поисках и запросах можно использовать только те поля, которые включены в файл load_fields. В файл load_fields всегда следует включать имена основного поля и как минимум одного векторного поля.

Вы также можете использовать skip_load_dynamic_field для определения необходимости загрузки динамического поля. Динамическое поле — это зарезервированное поле JSON с именем $meta, в котором все поля, не определённые схемой, и их значения сохраняются в виде пар «ключ-значение». При загрузке динамического поля все ключи в этих полях загружаются и становятся доступными для фильтрации и вывода. Если не все ключи динамического поля участвуют в фильтрации и выводе метаданных, установите для параметра skip_load_dynamic_field значение True.

Чтобы загрузить дополнительные поля после загрузки коллекции, необходимо сначала освободить коллекцию, чтобы избежать возможных ошибок, возникающих из-за изменений в индексе.

Освободить коллекцию

Поиск и запросы — это операции, требующие большого объема памяти. Для экономии ресурсов рекомендуется освободить коллекции, которые в данный момент не используются.

Следующий фрагмент кода демонстрирует, как освободить коллекцию.

# 8. Release the collection
client.release_collection(
    collection_name="my_collection"
)

res = client.get_load_state(
    collection_name="my_collection"
)

print(res)

# Output
#
# {
#     "state": "<LoadState: NotLoad>"
# }
import io.milvus.v2.service.collection.request.GetLoadStateReq;
import io.milvus.v2.service.collection.request.ReleaseCollectionReq;

// 8. Release the collection
ReleaseCollectionReq releaseCollectionReq = ReleaseCollectionReq.builder()
        .collectionName("my_collection")
        .build();

client.releaseCollection(releaseCollectionReq);

GetLoadStateReq loadStateReq = GetLoadStateReq.builder()
        .collectionName("my_collection")
        .build();
Boolean res = client.getLoadState(loadStateReq);
System.out.println(res);

// Output:
// false
import (
    "fmt"

    "github.com/milvus-io/milvus/client/v3/milvusclient"
)

err = client.ReleaseCollection(ctx, milvusclient.NewReleaseCollectionOption("my_collection"))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

state, err := client.GetLoadState(ctx, milvusclient.NewGetLoadStateOption("my_collection"))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}
fmt.Println(state.State)
use milvus::v2::prelude::*;

// 8. Release the collection
client
    .release_collection(
        ReleaseCollectionRequest::builder()
            .collection_name("my_collection")
            .build()?,
    )
    .await?;

let res = client
    .get_load_state(
        GetLoadStateRequest::builder()
            .collection_name("my_collection")
            .build()?,
    )
    .await?;

println!("{:?}", res.state());
auto status = client->ReleaseCollection(milvus::ReleaseCollectionRequest()
                                            .WithCollectionName("my_collection"));
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}

milvus::GetLoadStateResponse response;
status = client->GetLoadState(milvus::GetLoadStateRequest()
                                  .WithCollectionName("my_collection"),
                              response);
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}
std::cout << std::to_string(response.State()) << std::endl;
// 8. Release the collection
let res = await client.releaseCollection({
    collection_name: "my_collection"
})

console.log(res.error_code)

// Output
//
// Success
//

res = await client.getLoadState({
    collection_name: "my_collection"
})

console.log(res.state)

// Output
//
// LoadStateNotLoad
//
using Milvus.Client.V2.Requests.Collection;
using Milvus.Client.V2.Responses.Collection;
using Milvus.Client.V2.Types;

// 8. Release the collection
await client.ReleaseCollectionAsync(new ReleaseCollectionReq
{
    CollectionName = "my_collection"
});

// Get load state of the collection
GetLoadStateResp res = await client.GetLoadStateAsync(new GetLoadStateReq
{
    CollectionName = "my_collection"
});
Console.WriteLine(res.State);
export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/release" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--header "Request-Timeout: 10" \
-d '{
    "collectionName": "my_collection"
}'

# {
#     "code": 0,
#     "data": {}
# }

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/get_load_state" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--header "Request-Timeout: 10" \
-d '{
    "collectionName": "my_collection"
}'

# {
#     "code": 0,
#     "data": {
#         "loadState": "LoadStateNotLoad"
#     }
# }

ПереведеноDeepL

Попробуйте Managed Milvus бесплатно

Zilliz Cloud работает без проблем, поддерживается Milvus и в 10 раз быстрее.

Начать
Обратная связь

Была ли эта страница полезной?