エンティティのカウント
この記事では、コレクション内のエンティティをカウントする方法と、エンティティ数が実際の数と異なる場合がある理由について説明します。
概要
Zilliz Cloud では、コレクション内のエンティティをカウントする 2 つの方法を提供しています。
-
count(*)を出力フィールドとするクエリコレクション内の正確なエンティティ数を取得するには、この方法を使用し、次の点を確認してください。
-
対象コレクションをロードしていること。
-
クエリリクエストで
consistency_levelをStrongに設定していること。 -
output_fieldを['count(*)']に設定していること。
このようなクエリを受信すると、Zilliz Cloud はクエリノードにリクエストを送信し、すでにメモリにロードされているエンティティをカウントします。
クエリで複数のパーティション名を指定すると、これらのパーティションの対応するエンティティ数を取得できます。詳細については、count(*) を出力フィールドとするクエリ を参照してください。
-
-
get_collection_stats()を使用する上記の方法を使用するとコレクションの正確な数を取得できますが、どこでも使用することは推奨されません。この処理は基本的にクエリであり、頻繁に呼び出すとネットワークのジッターが発生したり、ビジネスに関連する検索やクエリに影響を与えたりする可能性があります。
精度が主な関心事でない場合は、代わりに
get_collection_stats()とget_partition_stats()を使用してください。この呼び出しは推定のエンティティ数を提供しますが、実行するために対象コレクションをロードする必要がなく、内部トラッカーが記録した内容を報告するだけなのでコストは無視できるほど小さいです。参考までに、すべてのデータ操作は非同期であるため、内部トラッカーはエンティティ数をリアルタイムに反映できません。詳細については、get_collection_stats() の使用 を参照してください。
上記の両方の方法では、同じプライマリキーを持つエンティティを別々のエンティティとしてカウントします。
プログラムでエンティティ数を取得する代わりに、Zilliz Cloud コンソールでクラスター、コレクション、またはパーティションの数値を確認することもできます。詳細については、Zilliz Cloud コンソールでのエンティティ数 を参照してください。
count(*) を出力フィールドとするクエリ
正確なエンティティ数を取得するには、コレクションをロードし、count(*) を出力フィールドとするクエリを実行して、クエリの整合性レベルを Strong に設定します。
- Python
- Java
- Go
- Rust
- C++
- NodeJS
- cURL
# Count without the entities in growing segments
res = client.query(
collection_name="test_collection",
output_fields=['count(*)']
)
# Count with the entities in growing segments
res = client.query(
collection_name="test_collection",
output_fields=['count(*)'],
consistency_level="Strong"
)
# Count the entities in a specific partition
res = client.query(
collection_name="test_collection",
output_fields=['count(*)'],
partition_names=['_default']
)
# Get the entity count
print(res[0]['count(*)'])
# Output
# 20
import io.milvus.v2.common.ConsistencyLevel;
import io.milvus.v2.service.vector.request.QueryReq;
import io.milvus.v2.service.vector.response.QueryResp;
import java.util.*;
// Count without the entities in growing segments
QueryResp count = client.query(QueryReq.builder()
.collectionName("test_collection")
.filter("")
.outputFields(Collections.singletonList("count(*)"))
.build());
// Count with the entities in growing segments
count = client.query(QueryReq.builder()
.collectionName("test_collection")
.filter("")
.outputFields(Collections.singletonList("count(*)"))
.consistencyLevel(ConsistencyLevel.STRONG)
.build());
// Count the entities in a specific partition
QueryResp countR = client.query(QueryReq.builder()
.collectionName("test_collection")
.filter("")
.outputFields(Collections.singletonList("count(*)"))
.partitionNames(Collections.singletonList("_default"))
.build());
System.out.print(count.getQueryResults().get(0).getEntity().get("count(*)"));
// Output
// 20
import (
"context"
"fmt"
"github.com/milvus-io/milvus/client/v3/entity"
"github.com/milvus-io/milvus/client/v3/milvusclient"
)
// Count without the entities in growing segments
resultSet, err := client.Query(ctx, milvusclient.NewQueryOption("test_collection").
WithFilter("").
WithOutputFields("count(*)"))
if err != nil {
fmt.Println(err.Error())
// handle error
}
fmt.Println("count: ", resultSet.GetColumn("count(*)").FieldData().GetScalars())
// Count with the entities in growing segments
resultSet, err = client.Query(ctx, milvusclient.NewQueryOption("test_collection").
WithFilter("").
WithOutputFields("count(*)").
WithConsistencyLevel(entity.ClStrong))
if err != nil {
fmt.Println(err.Error())
// handle error
}
fmt.Println("count: ", resultSet.GetColumn("count(*)").FieldData().GetScalars())
// Count the entities in a specific partition
resultSet, err = client.Query(ctx, milvusclient.NewQueryOption("test_collection").
WithFilter("").
WithOutputFields("count(*)").
WithPartitions("_default"))
if err != nil {
fmt.Println(err.Error())
// handle error
}
fmt.Println("count: ", resultSet.GetColumn("count(*)").FieldData().GetScalars())
use milvus::v2::prelude::*;
// 1. Connect to Milvus
let client = ClientV2::new(&ConnectConfig::new().uri("YOUR_CLUSTER_ENDPOINT").token("YOUR_CLUSTER_TOKEN")).await?;
// 2. Count without the entities in growing segments
let response = client
.query(
QueryRequest::builder()
.collection_name("test_collection")
.output_fields(["count(*)"])
.build()?,
)
.await?;
println!("count: {}", response.results().rows()?.next().unwrap().get_i64("count(*)")?);
// 3. Count with the entities in growing segments
let response = client
.query(
QueryRequest::builder()
.collection_name("test_collection")
.output_fields(["count(*)"])
.consistency_level(ConsistencyLevel::Strong)
.build()?,
)
.await?;
println!("count: {}", response.results().rows()?.next().unwrap().get_i64("count(*)")?);
// 4. Count the entities in a specific partition
let response = client
.query(
QueryRequest::builder()
.collection_name("test_collection")
.output_fields(["count(*)"])
.partition_names(["_default"])
.build()?,
)
.await?;
println!("count: {}", response.results().rows()?.next().unwrap().get_i64("count(*)")?);
#include <iostream>
#include "milvus/MilvusClientV2.h"
auto client = milvus::MilvusClientV2::Create();
milvus::ConnectParam connect_param{"YOUR_CLUSTER_ENDPOINT", "YOUR_CLUSTER_TOKEN"};
auto status = client->Connect(connect_param);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
auto request = milvus::QueryRequest()
.WithCollectionName("test_collection")
.AddOutputField("count(*)");
milvus::QueryResponse response;
status = client->Query(request, response);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
request = milvus::QueryRequest()
.WithCollectionName("test_collection")
.AddOutputField("count(*)")
.WithConsistencyLevel(milvus::ConsistencyLevel::STRONG);
status = client->Query(request, response);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
request = milvus::QueryRequest()
.WithCollectionName("test_collection")
.AddOutputField("count(*)")
.AddPartitionName("_default");
status = client->Query(request, response);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
std::cout << response.Results().GetRowCount() << std::endl;
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";
const address = "YOUR_CLUSTER_ENDPOINT";
const token = "YOUR_CLUSTER_TOKEN";
const client = new MilvusClient({address, token});
// Count without the entities in growing segments
let res = await client.query({
collection_name: "test_collection",
output_fields: ["count(*)"]
});
// Count with the entities in growing segments
res = await client.query({
collection_name: "test_collection",
output_fields: ["count(*)"],
consistency_level: 'Strong'
});
// Count the entities in a specific partition
res = await client.query({
collection_name: "test_collection",
output_fields: ["count(*)"],
partition_names: ['_default']
});
// Get the entity count
console.log(res.data[0]['count(*)'])
// Output
// 20
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/query" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--header "Request-Timeout: 10" \
-d '{
"collectionName": "test_collection",
"filter": "",
"outputFields": ["count(*)"]
}'
#{"code":0,"cost":0,"data":[{count: 20}]}
get_collection_stats() の使用
前述のとおり、get_collection_stats() はコレクション内のエンティティ数の推定値を返します。これは実際のエンティティ数と異なる場合があります。コレクションをロードせずにこれを参照として使用できます。
次の例では、test_collection という名前のコレクションが存在することを前提としています。
- Python
- Java
- Go
- Rust
- C++
- NodeJS
- cURL
from pymilvus import MilvusClient
# 1. Set up a milvus client
client = MilvusClient(
uri="YOUR_CLUSTER_ENDPOINT",
token="YOUR_CLUSTER_TOKEN"
)
# 2. Get the entity count of a collection
client.get_collection_stats(collection_name="test_collection")
# Output
#
# {
# 'row_count': 1000
# }
# 3. Get the entity count of a partition
client.get_partition_stats(
collection_name="test_collection",
partition_name="_default"
)
# Output
#
# {
# 'row_count': 1000
# }
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import io.milvus.v2.service.collection.request.GetCollectionStatsReq;
import io.milvus.v2.service.collection.response.GetCollectionStatsResp;
import io.milvus.v2.service.partition.request.GetPartitionStatsReq;
import io.milvus.v2.service.partition.response.GetPartitionStatsResp;
// 1. Set up a milvus client
MilvusClientV2 client = new MilvusClientV2(ConnectConfig.builder()
.uri("YOUR_CLUSTER_ENDPOINT")
.token("YOUR_CLUSTER_TOKEN")
.build());
// 2. Get the entity count of a collection
GetCollectionStatsResp stats = client.getCollectionStats(GetCollectionStatsReq.builder()
.collectionName("test_collection")
.build());
System.out.print(stats.getNumOfEntities());
// 3. Get the entity count of a partition
GetPartitionStatsResp partitionStats = client.getPartitionStats(GetPartitionStatsReq.builder()
.collectionName("test_collection")
.partitionName("_default")
.build());
System.out.print(partitionStats.getNumOfEntities());
import (
"context"
"fmt"
"github.com/milvus-io/milvus/client/v3/milvusclient"
)
// 1. Get the entity count of a collection
stats, err := client.GetCollectionStats(ctx, milvusclient.NewGetCollectionStatsOption("test_collection"))
if err != nil {
fmt.Println(err.Error())
// handle error
}
fmt.Println("row_count: ", stats["row_count"])
// 2. Get the entity count of a partition
partitionStats, err := client.GetPartitionStats(ctx, milvusclient.NewGetPartitionStatsOption("test_collection", "_default"))
if err != nil {
fmt.Println(err.Error())
// handle error
}
fmt.Println("row_count: ", partitionStats["row_count"])
use milvus::v2::prelude::*;
// 1. Connect to Milvus
let client = ClientV2::new(&ConnectConfig::new().uri("YOUR_CLUSTER_ENDPOINT").token("YOUR_CLUSTER_TOKEN")).await?;
// 2. Get the entity count of a collection
let stats = client
.get_collection_stats(
GetCollectionStatsRequest::builder()
.collection_name("test_collection")
.build()?,
)
.await?;
println!("row_count: {:?}", stats.row_count());
// 3. Get the entity count of a partition
let partition_stats = client
.get_partition_stats(
GetPartitionStatsRequest::builder()
.collection_name("test_collection")
.partition_name("_default")
.build()?,
)
.await?;
println!("row_count: {:?}", partition_stats.row_count());
#include <iostream>
#include "milvus/MilvusClientV2.h"
auto client = milvus::MilvusClientV2::Create();
milvus::ConnectParam connect_param{"YOUR_CLUSTER_ENDPOINT", "YOUR_CLUSTER_TOKEN"};
auto status = client->Connect(connect_param);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
milvus::GetCollectionStatsResponse response;
status = client->GetCollectionStats(milvus::GetCollectionStatsRequest()
.WithCollectionName("test_collection"), response);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
milvus::GetPartitionStatsResponse partition_response;
status = client->GetPartitionStatistics(milvus::GetPartitionStatsRequest()
.WithCollectionName("test_collection")
.WithPartitionName("_default"), partition_response);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
std::cout << response.Stats().RowCount() << std::endl;
std::cout << partition_response.Stats().RowCount() << std::endl;
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";
// 1. Set up a milvus client
const milvusClient = new MilvusClient({
address: 'YOUR_CLUSTER_ENDPOINT',
token: 'YOUR_CLUSTER_TOKEN'
});
// 2. Get the entity count
await milvusClient.getCollectionStats({
collection_name: 'test_collection'
});
// 3. Get the entity count of a partition
await milvusClient.getPartitionStats({
collection_name: 'test_collection',
partition_name: '_default'
});
// Output
//
// {
// data: {'row_count': 1000 }
// }
export CLUSTER_ENDPOINT="YOUR_CLUSTER_ENDPOINT"
export TOKEN="YOUR_CLUSTER_TOKEN"
# Get the entity count of a collection
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/collections/get_stats" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"collectionName": "test_collection"
}'
#{"code":0,"data":{"rowCount":1000}}
# Get the entity count of a partition
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/partitions/get_stats" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
"collectionName": "test_collection",
"partitionName": "_default"
}'
#{"code":0,"data":{"rowCount":1000}}
Zilliz Cloud コンソールでのエンティティ数
プログラムでエンティティをカウントする代わりに、Zilliz Cloud コンソールにアクセスして、次のページでクラスター、コレクション、またはパーティションのエンティティ数を確認することもできます。
メトリクス
クラスターの Entity Count と Loaded Entities (Approx.) は、その Metrics タブで確認できます。どちらの値も推定値です。曲線内の値は get_collection_stats() を使用して取得されます。これ以上データの挿入や削除がなければ、Entity Count の曲線は最終的に現在のコレクションの実際のエンティティ数を反映します。

コレクションの詳細
コレクションの実際のエンティティ数は、その詳細タブで確認できます。この値は、クエリで count(*) を出力フィールドとして使用することで取得されます。

パーティション
コレクションの Partitions タブを使用して、その子パーティション内のロード済みエンティティの推定数を確認することもできます。この値は、get_partition_stats() を使用して取得されます。

FAQ
-
get_collection_stats()またはget_partition_stats()を使用して取得したエンティティ数が、一部のエンティティを挿入した後で対象のコレクションまたはパーティションの実際のエンティティ数を反映しないのはなぜですか?これらの方法は内部トラッカーが記録した内容のみを報告するため、すべてのデータ操作が非同期であることから、実際のエンティティ数と異なる場合があります。
-
一部のエンティティを挿入または削除した後で、コレクションの Metrics タブにある Entity Count 曲線が変化しないのはなぜですか?
Entity Count 曲線の値は、特定の時点で推定されたものです。すべてのデータ操作が非同期であるため、曲線に反映されるまでに遅延が生じる場合があります。
-
一部のエンティティを挿入または削除した後で、コレクションの Partitions タブにある Entity Count (Approx.) 列に表示される値が変化しないのはなぜですか?
一覧表示されたパーティションに表示される値はすべて推定値です。すべてのデータ操作が非同期であるため、曲線に反映されるまでに遅延が生じる場合があります。
-
コレクションの Overview タブの Loaded Entities に表示される値が、コレクション内の実際のエンティティ数を反映しないのはなぜですか?
Loaded Entities に表示される値は正確です。この値と通常のクエリで取得されるエンティティ数との間に差がある場合、コレクション内の一部のエンティティが同じプライマリキーを持っている可能性があります。
count(*)を出力フィールドとするクエリは、同じプライマリキーを持つエンティティを別々のエンティティとして扱いますが、その他のクエリは、最終的な結果を返す前に同じプライマリキーを持つエンティティを省略します。