🚀 جرب Zilliz Cloud، الـ Milvus المدارة بالكامل، مجاناً — تجربة أداء أسرع بـ 10 أضعاف! جرب الآن>>

milvus-logo
LFAI
الصفحة الرئيسية
  • دليل المستخدم
  • Home
  • Docs
  • دليل المستخدم

  • المجموعات

  • إنشاء مجموعة

إنشاء مجموعة

يمكنك إنشاء مجموعة من خلال تحديد مخططها ومعلمات الفهرس ونوع القياس وما إذا كان سيتم تحميلها عند الإنشاء. تقدم هذه الصفحة كيفية إنشاء مجموعة من البداية.

نظرة عامة

المجموعة عبارة عن جدول ثنائي الأبعاد يحتوي على أعمدة ثابتة وصفوف متغيرة. يمثل كل عمود حقلاً، ويمثل كل صف كيانًا. يلزم وجود مخطط لتنفيذ إدارة البيانات الهيكلية هذه. يجب أن يفي كل كيان يتم إدراجه بالقيود المحددة في المخطط.

ويمكنك تحديد كل جانب من جوانب المجموعة، بما في ذلك مخططها ومعلمات الفهرس ونوع المقياس، وما إذا كان يجب تحميلها عند الإنشاء لضمان أن المجموعة تلبي متطلباتك بالكامل.

لإنشاء مجموعة، تحتاج إلى

إنشاء مخطط

يحدد المخطط بنية بيانات المجموعة. عند إنشاء مجموعة، تحتاج إلى تصميم المخطط بناءً على متطلباتك. لمزيد من التفاصيل، راجع شرح المخطط.

تُنشئ مقتطفات التعليمات البرمجية التالية مخططًا مع الحقل الديناميكي الممكّن وثلاثة حقول إلزامية باسم my_id و my_vector و my_varchar.

يمكنك تعيين القيم الافتراضية لأي حقل قياسي وجعلها قابلة للإلغاء. لمزيد من التفاصيل، راجع Nullable & Default.

# 3. Create a collection in customized setup mode
from pymilvus import MilvusClient, DataType

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

# 3.1. Create schema
schema = MilvusClient.create_schema(
    auto_id=False,
    enable_dynamic_field=True,
)

# 3.2. Add fields to schema
schema.add_field(field_name="my_id", datatype=DataType.INT64, is_primary=True)
schema.add_field(field_name="my_vector", datatype=DataType.FLOAT_VECTOR, dim=5)
schema.add_field(field_name="my_varchar", datatype=DataType.VARCHAR, max_length=512)

import io.milvus.v2.common.DataType;
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import io.milvus.v2.service.collection.request.AddFieldReq;
import io.milvus.v2.service.collection.request.CreateCollectionReq;

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

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

MilvusClientV2 client = new MilvusClientV2(connectConfig);

// 3. Create a collection in customized setup mode

// 3.1 Create schema
CreateCollectionReq.CollectionSchema schema = client.createSchema();

// 3.2 Add fields to schema
schema.addField(AddFieldReq.builder()
        .fieldName("my_id")
        .dataType(DataType.Int64)
        .isPrimaryKey(true)
        .autoID(false)
        .build());

schema.addField(AddFieldReq.builder()
        .fieldName("my_vector")
        .dataType(DataType.FloatVector)
        .dimension(5)
        .build());

schema.addField(AddFieldReq.builder()
        .fieldName("my_varchar")
        .dataType(DataType.VarChar)
        .maxLength(512)
        .build());

import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";

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

// 3. Create a collection in customized setup mode
// 3.1 Define fields
const fields = [
    {
        name: "my_id",
        data_type: DataType.Int64,
        is_primary_key: true,
        auto_id: false
    },
    {
        name: "my_vector",
        data_type: DataType.FloatVector,
        dim: 5
    },
    {
        name: "my_varchar",
        data_type: DataType.VarChar,
        max_length: 512
    }
]

import "github.com/milvus-io/milvus/client/v2/entity"

schema := entity.NewSchema().WithDynamicFieldEnabled(true).
        WithField(entity.NewField().WithName("my_id").WithIsAutoID(true).WithDataType(entity.FieldTypeInt64).WithIsPrimaryKey(true)).
        WithField(entity.NewField().WithName("my_vector").WithDataType(entity.FieldTypeFloatVector).WithDim(5)).
        WithField(entity.NewField().WithName("my_varchar").WithDataType(entity.FieldTypeVarChar).WithMaxLength(512))thDim(5))

export schema='{
        "autoId": false,
        "enabledDynamicField": false,
        "fields": [
            {
                "fieldName": "my_id",
                "dataType": "Int64",
                "isPrimary": true
            },
            {
                "fieldName": "my_vector",
                "dataType": "FloatVector",
                "elementTypeParams": {
                    "dim": "5"
                }
            },
            {
                "fieldName": "my_varchar",
                "dataType": "VarChar",
                "elementTypeParams": {
                    "max_length": 512
                }
            }
        ]
    }'

(اختياري) تعيين معلمات الفهرس

يؤدي إنشاء فهرس على حقل معين إلى تسريع البحث في هذا الحقل. يسجل الفهرس ترتيب الكيانات ضمن مجموعة. كما هو موضح في مقتطفات التعليمات البرمجية التالية، يمكنك استخدام metric_type و index_type لتحديد الطرق المناسبة لـ Milvus لفهرسة حقل ما وقياس أوجه التشابه بين تضمينات المتجهات.

في Milvus، يمكنك استخدام AUTOINDEX كنوع فهرس لجميع الحقول المتجهة، وأحد COSINE و L2 و IP كنوع القياس بناءً على احتياجاتك.

كما هو موضح في مقتطف الكود أعلاه، تحتاج إلى تعيين كل من نوع الفهرس والنوع المتري لحقول المتجهات ونوع الفهرس فقط للحقول القياسية. تعد الفهارس إلزامية للحقول المتجهة، ويُنصح بإنشاء فهارس للحقول القياسية المستخدمة بشكل متكرر في شروط التصفية.

لمزيد من التفاصيل، راجع الفهارس.

# 3.3. Prepare index parameters
index_params = client.prepare_index_params()

# 3.4. Add indexes
index_params.add_index(
    field_name="my_id",
    index_type="STL_SORT"
)

index_params.add_index(
    field_name="my_vector", 
    index_type="AUTOINDEX",
    metric_type="COSINE"
)

import io.milvus.v2.common.IndexParam;
import java.util.*;

// 3.3 Prepare index parameters
IndexParam indexParamForIdField = IndexParam.builder()
        .fieldName("my_id")
        .indexType(IndexParam.IndexType.STL_SORT)
        .build();

IndexParam indexParamForVectorField = IndexParam.builder()
        .fieldName("my_vector")
        .indexType(IndexParam.IndexType.AUTOINDEX)
        .metricType(IndexParam.MetricType.COSINE)
        .build();

List<IndexParam> indexParams = new ArrayList<>();
indexParams.add(indexParamForIdField);
indexParams.add(indexParamForVectorField);

// 3.2 Prepare index parameters
const index_params = [{
    field_name: "my_id",
    index_type: "STL_SORT"
},{
    field_name: "my_vector",
    index_type: "AUTOINDEX",
    metric_type: "COSINE"
}]

import (
    "github.com/milvus-io/milvus/client/v2"
    "github.com/milvus-io/milvus/client/v2/entity"
    "github.com/milvus-io/milvus/client/v2/index"
)

indexOptions := []client.CreateIndexOption{
    client.NewCreateIndexOption(collectionName, "my_vector", index.NewAutoIndex(entity.COSINE)).WithIndexName("my_vector"),
    client.NewCreateIndexOption(collectionName, "my_id", index.NewSortedIndex()).WithIndexName("my_id"),
}

export indexParams='[
        {
            "fieldName": "my_vector",
            "metricType": "COSINE",
            "indexName": "my_vector",
            "indexType": "AUTOINDEX"
        },
        {
            "fieldName": "my_id",
            "indexName": "my_id",
            "indexType": "STL_SORT"
        }
    ]'

إنشاء مجموعة

إذا قمت بإنشاء مجموعة مع معلمات الفهرس، يقوم ميلفوس تلقائيًا بتحميل المجموعة عند إنشائها. في هذه الحالة، تتم فهرسة جميع الحقول المذكورة في معلمات الفهرس.

تشرح مقتطفات التعليمات البرمجية التالية كيفية إنشاء المجموعة مع معلمات الفهرس والتحقق من حالة تحميلها.

# 3.5. Create a collection with the index loaded simultaneously
client.create_collection(
    collection_name="customized_setup_1",
    schema=schema,
    index_params=index_params
)

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

print(res)

# Output
#
# {
#     "state": "<LoadState: Loaded>"
# }

import io.milvus.v2.service.collection.request.CreateCollectionReq;
import io.milvus.v2.service.collection.request.GetLoadStateReq;

// 3.4 Create a collection with schema and index parameters
CreateCollectionReq customizedSetupReq1 = CreateCollectionReq.builder()
        .collectionName("customized_setup_1")
        .collectionSchema(schema)
        .indexParams(indexParams)
        .build();

client.createCollection(customizedSetupReq1);

// 3.5 Get load state of the collection
GetLoadStateReq customSetupLoadStateReq1 = GetLoadStateReq.builder()
        .collectionName("customized_setup_1")
        .build();

Boolean loaded = client.getLoadState(customSetupLoadStateReq1);
System.out.println(loaded);

// Output:
// true

// 3.3 Create a collection with fields and index parameters
res = await client.createCollection({
    collection_name: "customized_setup_1",
    fields: fields,
    index_params: index_params,
})

console.log(res.error_code)  

// Output
// 
// Success
// 

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

console.log(res.state)

// Output
// 
// LoadStateLoaded
// 

import "github.com/milvus-io/milvus/client/v2"

err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_1", schema).
    WithIndexOptions(indexOptions...),
)
if err != nil {
    // handle error
}
fmt.Println("collection created")

export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
    \"collectionName\": \"customized_setup_1\",
    \"schema\": $schema,
    \"indexParams\": $indexParams
}"

يمكنك أيضًا إنشاء مجموعة بدون أي معلمات فهرس وإضافتها بعد ذلك. في هذه الحالة، لا يقوم ميلفوس بتحميل المجموعة عند إنشائها. للحصول على تفاصيل حول كيفية إنشاء فهارس لمجموعة موجودة، راجع شرح الفهرس.

يوضح مقتطف الشيفرة التالي كيفية إنشاء مجموعة بدون فهرس، وتبقى حالة تحميل المجموعة غير محملة عند الإنشاء.

# 3.6. Create a collection and index it separately
client.create_collection(
    collection_name="customized_setup_2",
    schema=schema,
)

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

print(res)

# Output
#
# {
#     "state": "<LoadState: NotLoad>"
# }

// 3.6 Create a collection and index it separately
CreateCollectionReq customizedSetupReq2 = CreateCollectionReq.builder()
    .collectionName("customized_setup_2")
    .collectionSchema(schema)
    .build();

client.createCollection(customizedSetupReq2);

GetLoadStateReq customSetupLoadStateReq2 = GetLoadStateReq.builder()
        .collectionName("customized_setup_2")
        .build();
        
Boolean loaded = client.getLoadState(customSetupLoadStateReq2);
System.out.println(loaded);

// Output:
// false

// 3.4 Create a collection and index it seperately
res = await client.createCollection({
    collection_name: "customized_setup_2",
    fields: fields,
})

console.log(res.error_code)

// Output
// 
// Success
// 

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

console.log(res.state)

// Output
// 
// LoadStateNotLoad
// 

import "github.com/milvus-io/milvus/client/v2"

err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_2", schema))
if err != nil {
    // handle error
}
fmt.Println("collection created")

export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
    \"collectionName\": \"customized_setup_2\",
    \"schema\": $schema
}"

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

يوفر ميلفوس أيضًا طريقة لإنشاء مجموعة على الفور. لمزيد من التفاصيل، راجع إنشاء مجموعة على الفور.

تعيين خصائص المجموعة

يمكنك تعيين خصائص للمجموعة المراد إنشاؤها لجعلها ملائمة لخدمتك. الخصائص القابلة للتطبيق هي كما يلي.

تعيين رقم الشريحة

الأجزاء هي شرائح أفقية للمجموعة. تتوافق كل شريحة مع قناة إدخال بيانات. تحتوي كل مجموعة على شريحة بشكل افتراضي. يمكنك تعيين العدد المناسب من الشرائح عند إنشاء مجموعة استنادًا إلى الإنتاجية المتوقعة وحجم البيانات المراد إدراجها في المجموعة.

في الحالات الشائعة، ضع في اعتبارك زيادة عدد الأجزاء بمقدار جزء واحد في كل مرة يزيد فيها الإنتاجية المتوقعة بمقدار 500 ميجابايت/ثانية أو يزيد حجم البيانات المراد إدراجها بمقدار 100 جيجابايت. يستند هذا الاقتراح إلى تجربتنا الخاصة وقد لا يتناسب تمامًا مع سيناريوهات تطبيقك. يمكنك ضبط هذا الرقم ليناسب احتياجاتك الخاصة أو استخدام القيمة الافتراضية فقط.

يوضح مقتطف الشيفرة التالي كيفية تعيين رقم الجزء عند إنشاء مجموعة.

# With shard number
client.create_collection(
    collection_name="customized_setup_3",
    schema=schema,
    # highlight-next-line
    num_shards=1
)

// With shard number
CreateCollectionReq customizedSetupReq3 = CreateCollectionReq.builder()
    .collectionName("customized_setup_3")
    .collectionSchema(collectionSchema)
    // highlight-next-line
    .numShards(1)
    .build();
client.createCollection(customizedSetupReq3);

const createCollectionReq = {
    collection_name: "customized_setup_3",
    schema: schema,
    // highlight-next-line
    shards_num: 1
}

import "github.com/milvus-io/milvus/client/v2"

err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_3", schema).WithShardNum(1))
if err != nil {
    // handle error
}
fmt.Println("collection created")

export params='{
    "shardsNum": 1
}'

export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
    \"collectionName\": \"customized_setup_3\",
    \"schema\": $schema,
    \"params\": $params
}"

تمكين mmap

يتيح Milvus تمكين mmap على جميع المجموعات بشكل افتراضي، مما يسمح لـ Milvus بتعيين بيانات الحقل الخام في الذاكرة بدلاً من تحميلها بالكامل. هذا يقلل من آثار أقدام الذاكرة ويزيد من سعة المجموعة. للحصول على تفاصيل حول mmap، راجع استخدام mmap.

# With mmap
client.create_collection(
    collection_name="customized_setup_4",
    schema=schema,
    # highlight-next-line
    enable_mmap=False
)

import io.milvus.param.Constant;

// With MMap
CreateCollectionReq customizedSetupReq4 = CreateCollectionReq.builder()
        .collectionName("customized_setup_4")
        .collectionSchema(schema)
        // highlight-next-line
        .property(Constant.MMAP_ENABLED, "false")
        .build();
client.createCollection(customizedSetupReq4);

client.create_collection({
    collection_name: "customized_setup_4",
    schema: schema,
     properties: {
        'mmap.enabled': true,
     },
})

import (
    "github.com/milvus-io/milvus/client/v2"
    "github.com/milvus-io/milvus/pkg/common"
)

err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_4", schema).WithProperty(common.MmapEnabledKey, true))
if err != nil {
    // handle error
}
fmt.Println("collection created")

# Currently not available for REST

تعيين TTL للمجموعة

إذا كانت هناك حاجة إلى إسقاط مجموعة ما لفترة محددة، ففكر في تعيين وقت التشغيل بالثواني. بمجرد انتهاء مدة TTL، يقوم ميلفوس بحذف الكيانات في المجموعة وإسقاط المجموعة. يكون الحذف غير متزامن، مما يشير إلى أن عمليات البحث والاستعلامات لا تزال ممكنة قبل اكتمال الحذف.

يقوم مقتطف الكود التالي بتعيين TTL إلى يوم واحد (86400 ثانية). يُنصح بتعيين TTL إلى يومين كحد أدنى.

# With TTL
client.create_collection(
    collection_name="customized_setup_5",
    schema=schema,
    # highlight-start
    properties={
        "collection.ttl.seconds": 86400
    }
    # highlight-end
)

import io.milvus.param.Constant;

// With TTL
CreateCollectionReq customizedSetupReq5 = CreateCollectionReq.builder()
        .collectionName("customized_setup_5")
        .collectionSchema(schema)
        // highlight-next-line
        .property(Constant.TTL_SECONDS, "86400")
        .build();
client.createCollection(customizedSetupReq5);

const createCollectionReq = {
    collection_name: "customized_setup_5",
    schema: schema,
    // highlight-start
    properties: {
        "collection.ttl.seconds": 86400
    }
    // highlight-end
}

import (
    "github.com/milvus-io/milvus/client/v2"
    "github.com/milvus-io/milvus/pkg/common"
)

err = cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_5", schema).
        WithProperty(common.CollectionTTLConfigKey, 86400)) //  TTL in seconds
if err != nil {
        // handle error
}
fmt.Println("collection created")

export params='{
    "ttlSeconds": 86400
}'

export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
    \"collectionName\": \"customized_setup_5\",
    \"schema\": $schema,
    \"params\": $params
}"

تعيين مستوى الاتساق

عند إنشاء مجموعة، يمكنك تعيين مستوى الاتساق لعمليات البحث والاستعلامات في المجموعة. يمكنك أيضًا تغيير مستوى تناسق المجموعة أثناء بحث أو استعلام معين.

# With consistency level
client.create_collection(
    collection_name="customized_setup_6",
    schema=schema,
    # highlight-next
    consistency_level="Bounded",
)

import io.milvus.v2.common.ConsistencyLevel;

// With consistency level
CreateCollectionReq customizedSetupReq6 = CreateCollectionReq.builder()
        .collectionName("customized_setup_6")
        .collectionSchema(schema)
        // highlight-next-line
        .consistencyLevel(ConsistencyLevel.BOUNDED)
        .build();
client.createCollection(customizedSetupReq6);

const createCollectionReq = {
    collection_name: "customized_setup_6",
    schema: schema,
    // highlight-next
    consistency_level: "Bounded",
    // highlight-end
}

client.createCollection(createCollectionReq);

import (
    "github.com/milvus-io/milvus/client/v2"
    "github.com/milvus-io/milvus/client/v2/entity"
)

err := cli.CreateCollection(ctx, client.NewCreateCollectionOption("customized_setup_6", schema).
    WithConsistencyLevel(entity.ClBounded))
if err != nil {
    // handle error
}
fmt.Println("collection created")

export params='{
    "consistencyLevel": "Bounded"
}'

export CLUSTER_ENDPOINT="http://localhost:19530"
export TOKEN="root:Milvus"

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/create" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d "{
    \"collectionName\": \"customized_setup_6\",
    \"schema\": $schema,
    \"params\": $params
}"

لمعرفة المزيد عن مستويات الاتساق، راجع مستوى الاتساق.

تمكين الحقل الديناميكي

الحقل الديناميكي في المجموعة هو حقل تدوين كائنات جافا سكريبت (JSON) محجوز باسم $meta. بمجرد تمكين هذا الحقل، يحفظ Milvus جميع الحقول غير المعرفة من قبل الهيكلية التي يحملها كل كيان وقيمها كأزواج قيمة مفتاح في الحقل المحجوز.

للحصول على تفاصيل حول كيفية استخدام الحقل الديناميكي، راجع الحقل الديناميكي.

جرب Managed Milvus مجاناً

Zilliz Cloud خالي من المتاعب، ويعمل بواسطة Milvus ويعمل بسرعة 10 أضعاف.

ابدأ
التعليقات

هل كانت هذه الصفحة مفيدة؟