• Milvusについて
  • スタート
  • コンセプト
  • ユーザーガイド
    • コレクション
    • スキーマとデータフィールド
    • 挿入と削除
    • インデックス
    • 検索
    • 関数とモデル推論
    • ストレージの最適化
    • スナップ写真
  • データインポート
  • AIツール
  • 管理ガイド
  • ツール
  • 統合
  • チュートリアル
  • よくあるご質問
  • API Reference

BM25関数

BM25関数は、生のテキストを疎なベクトルに変換し、語彙的関連性に基づいて文書をスコアリングすることにより、全文検索を可能にする。用語ベースのマッチングと頻度を考慮した重み付けを適用し、クエリ用語と密接に一致するテキスト文書の効率的な検索をサポートする。

ローカルテキスト関数であるBM25関数はMilvus内で実行され、モデル推論や外部統合を必要としない。テキストベースの検索シナリオにおいて、決定論的で透過的な検索メカニズムを提供します。

BM25の仕組み

BM25アルゴリズムは全文検索で広く使用されている用語ベースの関連性スコアリングアルゴリズムです。Milvusでは、BM25をスパース検索パイプラインとして実装し、テキストをタームウェイト表現に変換し、分散スパースインデックスを使用してトップK文書を検索する。

全体的なワークフローは、同じテキスト解析ロジックを共有する文書取り込みと クエリテキスト処理の2つの対称パスから構成される。

文書の取り込みテキストからスパース表現へ

文書が挿入されると、その生テキストはまずアナライザで処理され、アナライザはテキストを個々の用語にトークン化する。

例えば、ドキュメント

"We are loving Milvus!"

という文書は、次のような用語に分析される:

["we", "love", "milvus"]

次に、各文書は用語頻度(TF)表現として表現され、各用語が文書に何回現れるかを記録する。例えば

{
  "we": 1,
  "love": 1,
  "milvus": 1
}

同時に、Milvusは以下のようなコーパスレベルの統計情報を更新する:

  • 各用語の文書出現頻度 (DF)

  • 平均文書長

  • 各用語とそれを含む文書を対応付ける投稿リスト

文書のTF表現はスパース埋め込みに挿入され、そこに投稿された用語はスケーラブルな検索のためにノード間で分割される。

クエリテキスト処理:IDF重み付けの適用

テキストベースのクエリが発行されると、文書取り込みの際に使用されたのと同じアナライザによって処理され、一貫した用語のセグメンテーションが保証される。

例えば

"who loves Milvus?"

は次のように分析される:

["who", "love", "milvus"]

Milvusは各クエリ用語について、コーパス統計からその逆文書頻度(IDF)を調べる。IDFはデータセット全体における用語の情報量を反映し、稀な用語は高い重み付けを受け、一般的な用語は低い重み付けを受ける。

概念的には、これはIDFで重み付けされたクエリー用語のセットを生成する:

{
  "who": 0.1,
  "love": 0.5,
  "milvus": 1.2
}

BM25スコアリングとトップK検索

BM25は、マッチしたクエリ用語に基づいて関連性スコアを計算し、文書をランク付けする。スコアリングは用語レベルで行われ、文書レベルで集計される。

用語レベルでのスコアリング

文書に出現する各クエリ用語について、BM25は用語レベルのスコアを計算する:

term_score =
  IDF(term) ×
  TF_boost(term, document, k1) ×
  length_normalization(document, b)

ここで

  • IDF(term)は、その用語がコレクション内でどれだけレアであるかを反映する。

  • TF_boost(...,k1)は用語の頻度とともに増加するが、頻度が高くなるにつれて飽和する。

  • length_normalization(..., b)は文書の長さに基づいてスコアを調整する。

文書レベルのスコアリングとTop-K検索

最終的な文書スコアは、マッチした全てのクエリー用語の用語レベルスコアの合計である:

document_score =
  sum of term_score over all matched query terms

ドキュメントは最終スコアでランク付けされ、上位K個の高得点ドキュメントが返されます。

始める前に

BM25機能を使用する前に、コレクションスキーマを計画し、それが字句解析的なフルテキスト検索をサポートしていることを確認してください:

  • 生コンテンツのテキストフィールド

    コレクションには、生のテキストを格納するVARCHAR フィールドが必要です。このフィールドは、全文検索のために処理されるテキストのソースです。

  • テキストフィールドのアナライザ

    テキストフィールドはアナライザを有効にする必要があります。アナライザは、BM25関数によって語彙関連性が計算される前に、テキストがどのようにトークン化され、正規化されるかを定義します。

    デフォルトでは、Milvusは空白と句読点に基づいてテキストをトークン化するアナライザを内蔵しています。カスタム トークン化または正規化の動作が必要な場合は、カスタム アナライザを定義することができます。詳細については、「ユースケースに適したアナライザを選択する」を参照してください。

  • BM25出力用の疎ベクトル

    コレクションには、BM25関数によって生成されたスパース表現を格納するSPARSE_FLOAT_VECTOR フィールドを含める必要があります。このフィールドは、全文検索時のインデックス作成と検索に使用されます。

これらのスキーマレベルの考慮事項を把握した後、コレクションの作成と BM25 関数の使用に進みます。

ステップ 1: BM25 関数でコレクションを作成する

BM25関数を使用するには、コレクションを作成するときに関数を定義する必要があります。関数はコレクション・スキーマの一部となり、データ挿入と検索時に自動的に適用されます。

スキーマフィールドの定義

コレクションスキーマには、少なくとも3つの必須フィールドを含める必要があります:

  • プライマリフィールド:コレクション内の各エンティティを一意に識別する。

  • テキストフィールド(VARCHAR):生のテキスト文書を格納する。Milvus が BM25 関連性ランキングのためにテキストを処理できるように、enable_analyzer=True を設定する必要があります。デフォルトでは、Milvusはテキスト分析にアナライザを使用します。 standard アナライザを使用します。別のアナライザを設定するには、アナライザの概要を参照してください。

  • スパースベクトルフィールド(SPARSE_FLOAT_VECTOR):BM25関数によって自動的に生成されたスパース埋め込みを格納する。

from pymilvus import MilvusClient, DataType, Function, FunctionType

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

schema = client.create_schema()

schema.add_field(field_name="id", datatype=DataType.INT64, is_primary=True, auto_id=True) # Primary field
schema.add_field(field_name="text", datatype=DataType.VARCHAR, max_length=1000, enable_analyzer=True) # Text field
schema.add_field(field_name="sparse", datatype=DataType.SPARSE_FLOAT_VECTOR) # Sparse vector field; no dim required for sparse vectors
import io.milvus.v2.common.DataType;
import io.milvus.v2.service.collection.request.AddFieldReq;
import io.milvus.v2.service.collection.request.CreateCollectionReq;

CreateCollectionReq.CollectionSchema schema = CreateCollectionReq.CollectionSchema.builder()
        .build();
schema.addField(AddFieldReq.builder()
        .fieldName("id")
        .dataType(DataType.Int64)
        .isPrimaryKey(true)
        .autoID(true)
        .build());
schema.addField(AddFieldReq.builder()
        .fieldName("text")
        .dataType(DataType.VarChar)
        .maxLength(1000)
        .enableAnalyzer(true)
        .build());
schema.addField(AddFieldReq.builder()
        .fieldName("sparse")
        .dataType(DataType.SparseFloatVector)
        .build());
import (
    "context"
    "fmt"

    "github.com/milvus-io/milvus/client/v2/column"
    "github.com/milvus-io/milvus/client/v2/entity"
    "github.com/milvus-io/milvus/client/v2/index"
    "github.com/milvus-io/milvus/client/v2/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)

schema := entity.NewSchema()
schema.WithField(entity.NewField().
    WithName("id").
    WithDataType(entity.FieldTypeInt64).
    WithIsPrimaryKey(true).
    WithIsAutoID(true),
).WithField(entity.NewField().
    WithName("text").
    WithDataType(entity.FieldTypeVarChar).
    WithEnableAnalyzer(true).
    WithMaxLength(1000),
).WithField(entity.NewField().
    WithName("sparse").
    WithDataType(entity.FieldTypeSparseVector),
)
import { MilvusClient, DataType } from "@zilliz/milvus2-sdk-node";

const address = "http://localhost:19530";
const token = "root:Milvus";
const client = new MilvusClient({address, token});
const schema = [
  {
    name: "id",
    data_type: DataType.Int64,
    is_primary_key: true,
  },
  {
    name: "text",
    data_type: "VarChar",
    enable_analyzer: true,
    enable_match: true,
    max_length: 1000,
  },
  {
    name: "sparse",
    data_type: DataType.SparseFloatVector,
  },
];

console.log(res.results)
export schema='{
        "autoId": true,
        "enabledDynamicField": false,
        "fields": [
            {
                "fieldName": "id",
                "dataType": "Int64",
                "isPrimary": true
            },
            {
                "fieldName": "text",
                "dataType": "VarChar",
                "elementTypeParams": {
                    "max_length": 1000,
                    "enable_analyzer": true
                }
            },
            {
                "fieldName": "sparse",
                "dataType": "SparseFloatVector"
            }
        ]
    }'

BM25 関数の定義

BM25関数はトークン化されたテキストをBM25スコアリングをサポートするスパースベクトルに変換します。

関数を定義し、スキーマに追加します:

bm25_function = Function(
    name="text_bm25_emb", # Function name
    input_field_names=["text"], # Name of the VARCHAR field containing raw text data
    output_field_names=["sparse"], # Name of the SPARSE_FLOAT_VECTOR field reserved to store generated embeddings
    function_type=FunctionType.BM25, # Set to `BM25`
)

schema.add_function(bm25_function)
import io.milvus.common.clientenum.FunctionType;
import io.milvus.v2.service.collection.request.CreateCollectionReq.Function;

import java.util.*;

schema.addFunction(Function.builder()
        .functionType(FunctionType.BM25)
        .name("text_bm25_emb")
        .inputFieldNames(Collections.singletonList("text"))
        .outputFieldNames(Collections.singletonList("sparse"))
        .build());
function := entity.NewFunction().
    WithName("text_bm25_emb").
    WithInputFields("text").
    WithOutputFields("sparse").
    WithType(entity.FunctionTypeBM25)
schema.WithFunction(function)
const functions = [
    {
      name: 'text_bm25_emb',
      description: 'bm25 function',
      type: FunctionType.BM25,
      input_field_names: ['text'],
      output_field_names: ['sparse'],
      params: {},
    },
];
export schema='{
        "autoId": true,
        "enabledDynamicField": false,
        "fields": [
            {
                "fieldName": "id",
                "dataType": "Int64",
                "isPrimary": true
            },
            {
                "fieldName": "text",
                "dataType": "VarChar",
                "elementTypeParams": {
                    "max_length": 1000,
                    "enable_analyzer": true
                }
            },
            {
                "fieldName": "sparse",
                "dataType": "SparseFloatVector"
            }
        ],
        "functions": [
            {
                "name": "text_bm25_emb",
                "type": "BM25",
                "inputFieldNames": ["text"],
                "outputFieldNames": ["sparse"],
                "params": {}
            }
        ]
    }'

インデックスの設定

必要なフィールドと組み込み関数でスキーマを定義した後、コレクションのインデックスを設定します。

index_params = client.prepare_index_params()

index_params.add_index(
    field_name="sparse",

    index_type="SPARSE_INVERTED_INDEX",
    metric_type="BM25",
    params={
        "inverted_index_algo": "DAAT_MAXSCORE",
        "bm25_k1": 1.2,
        "bm25_b": 0.75
    }

)
import io.milvus.v2.common.IndexParam;

Map<String,Object> params = new HashMap<>();
params.put("inverted_index_algo", "DAAT_MAXSCORE");
params.put("bm25_k1", 1.2);
params.put("bm25_b", 0.75);

List<IndexParam> indexes = new ArrayList<>();
indexes.add(IndexParam.builder()
        .fieldName("sparse")
        .indexType(IndexParam.IndexType.AUTOINDEX)
        .metricType(IndexParam.MetricType.BM25)
        .extraParams(params)
        .build());
indexOption := milvusclient.NewCreateIndexOption("my_collection", "sparse",
    index.NewAutoIndex(entity.MetricType(entity.BM25)))
    .WithExtraParam("inverted_index_algo", "DAAT_MAXSCORE")
    .WithExtraParam("bm25_k1", 1.2)
    .WithExtraParam("bm25_b", 0.75)
const index_params = [
  {
    field_name: "sparse",
    metric_type: "BM25",
    index_type: "SPARSE_INVERTED_INDEX",
    params: {
        "inverted_index_algo": "DAAT_MAXSCORE",
        "bm25_k1": 1.2,
        "bm25_b": 0.75
    }
  },
];
export indexParams='[
        {
            "fieldName": "sparse",
            "metricType": "BM25",
            "indexType": "AUTOINDEX",
            "params":{
               "inverted_index_algo": "DAAT_MAXSCORE",
               "bm25_k1": 1.2,
               "bm25_b": 0.75
            }
        }
    ]'

コレクションの作成

定義したスキーマとインデックスのパラメータを使用して、コレクションを作成します:

client.create_collection(
    collection_name='my_collection',
    schema=schema,
    index_params=index_params
)
import io.milvus.v2.service.collection.request.CreateCollectionReq;

CreateCollectionReq requestCreate = CreateCollectionReq.builder()
        .collectionName("my_collection")
        .collectionSchema(schema)
        .indexParams(indexes)
        .build();
client.createCollection(requestCreate);
err = client.CreateCollection(ctx,
    milvusclient.NewCreateCollectionOption("my_collection", schema).
        WithIndexOptions(indexOption))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}
await client.create_collection(
    collection_name: 'my_collection',
    schema: schema,
    index_params: index_params,
    functions: functions
);
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" \
--header "Request-Timeout: 10" \
-d "{
    \"collectionName\": \"my_collection\",
    \"schema\": $schema,
    \"indexParams\": $indexParams
}"

BM25 関数を持つコレクションが作成されると、テキストを挿入し、テキストクエリに基づいて字句検索を実行できます。

ステップ 2: テキストデータをコレクションに挿入する

コレクションとインデックスを設定すると、テキストデータを挿入する準備ができます。このプロセスでは、生のテキストを提供するだけです。先ほど定義したBM25関数は、各テキストエントリのスパースベクトルを自動的に生成します。

client.insert('my_collection', [
    {'text': 'information retrieval is a field of study.'},
    {'text': 'information retrieval focuses on finding relevant information in large datasets.'},
    {'text': 'data mining and information retrieval overlap in research.'},
])
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import io.milvus.v2.service.vector.request.InsertReq;

Gson gson = new Gson();
List<JsonObject> rows = Arrays.asList(
        gson.fromJson("{\"text\": \"information retrieval is a field of study.\"}", JsonObject.class),
        gson.fromJson("{\"text\": \"information retrieval focuses on finding relevant information in large datasets.\"}", JsonObject.class),
        gson.fromJson("{\"text\": \"data mining and information retrieval overlap in research.\"}", JsonObject.class)
);

client.insert(InsertReq.builder()
        .collectionName("my_collection")
        .data(rows)
        .build());
// go
await client.insert({
collection_name: 'my_collection',
data: [
    {'text': 'information retrieval is a field of study.'},
    {'text': 'information retrieval focuses on finding relevant information in large datasets.'},
    {'text': 'data mining and information retrieval overlap in research.'},
]);
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/insert" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--header "Request-Timeout: 10" \
-d '{
    "data": [
        {"text": "information retrieval is a field of study."},
        {"text": "information retrieval focuses on finding relevant information in large datasets."},
        {"text": "data mining and information retrieval overlap in research."}
    ],
    "collectionName": "my_collection"
}'

ステップ3:テキストクエリーによる検索

データをコレクションに挿入したら、生のテキストクエリを使用して全文検索を実行できます。Milvusは自動的にクエリをスパースベクトルに変換し、BM25アルゴリズムを使ってマッチした検索結果をランク付けし、トップK(limit)の結果を返します。

search_params = {

}

res = client.search(
    collection_name='my_collection',
    data=['whats the focus of information retrieval?'],
    anns_field='sparse',
    output_fields=['text'], # Fields to return in search results; sparse field cannot be output
    limit=3,
    search_params=search_params
)

print(res)
import io.milvus.v2.service.vector.request.SearchReq;
import io.milvus.v2.service.vector.request.data.EmbeddedText;
import io.milvus.v2.service.vector.response.SearchResp;

Map<String,Object> searchParams = new HashMap<>();

SearchResp searchResp = client.search(SearchReq.builder()
        .collectionName("my_collection")
        .data(Collections.singletonList(new EmbeddedText("whats the focus of information retrieval?")))
        .annsField("sparse")
        .topK(3)
        .searchParams(searchParams)
        .outputFields(Collections.singletonList("text"))
        .build());
annSearchParams := index.NewCustomAnnParam()
resultSets, err := client.Search(ctx, milvusclient.NewSearchOption(
    "my_collection", // collectionName
    3,               // limit
    []entity.Vector{entity.Text("whats the focus of information retrieval?")},
).WithConsistencyLevel(entity.ClStrong).
    WithANNSField("sparse").
    WithAnnParam(annSearchParams).
    WithOutputFields("text"))
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

for _, resultSet := range resultSets {
    fmt.Println("IDs: ", resultSet.IDs.FieldData().GetScalars())
    fmt.Println("Scores: ", resultSet.Scores)
    fmt.Println("text: ", resultSet.GetColumn("text").FieldData().GetScalars())
}
await client.search(
    collection_name: 'my_collection',
    data: ['whats the focus of information retrieval?'],
    anns_field: 'sparse',
    output_fields: ['text'],
    limit: 3,

)
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/search" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--header "Request-Timeout: 10" \
--data-raw '{
    "collectionName": "my_collection",
    "data": [
        "whats the focus of information retrieval?"
    ],
    "annsField": "sparse",
    "limit": 3,
    "outputFields": [
        "text"
    ],
    "searchParams":{
        "params":{}
    }
}'