🚀 免費嘗試 Zilliz Cloud,完全托管的 Milvus,體驗速度提升 10 倍!立即嘗試

milvus-logo
LFAI
主頁
  • 使用者指南
  • Home
  • Docs
  • 使用者指南

  • 搜尋與重新排名

  • 文字匹配

文字匹配

Milvus 中的文字匹配可根據特定術語進行精確的文件檢索。此功能主要用於滿足特定條件的篩選搜尋,並可結合標量篩選來精細查詢結果,允許在符合標量條件的向量內進行相似性搜尋。

文字匹配著重於尋找查詢字詞的精確出現,而不會對匹配文件的相關性進行評分。如果您想要根據查詢字詞的語意和重要性擷取最相關的文件,我們建議您使用全文檢索。

概述

Milvus 整合了Tantivy來提供底層的倒排索引和基於詞彙的文字搜尋。對於每一個文本條目,Milvus 都會按照以下程序建立索引。

  1. 分析器:分析器會將輸入的文字標記化為單獨的字詞或標記,然後根據需要套用篩選器。這可讓 Milvus 根據這些標記建立索引。

  2. 建立索引:在文字分析之後,Milvus 會建立反向索引,將每個獨特的標記映射到包含該標記的文件。

當使用者執行文字比對時,倒置索引會被用來快速擷取所有包含該詞彙的文件。這比逐一掃描每個文件要快得多。

Text Match 文字匹配

啟用文字匹配

文字匹配對VARCHAR 欄位類型有效,它基本上是 Milvus 中的字串資料類型。要啟用文字匹配,請將enable_analyzerenable_match 都設定為True ,然後在定義收集模式時,選擇性地設定文字分析的分析器。

設定enable_analyzerenable_match

要啟用特定VARCHAR 欄位的文字匹配,在定義欄位模式時,將enable_analyzerenable_match 參數都設定為True 。這會指示 Milvus 將文字標記化,並為指定欄位建立反向索引,以進行快速有效的文字匹配。

from pymilvus import MilvusClient, DataType

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

schema.add_field(
    field_name='text', 
    datatype=DataType.VARCHAR, 
    max_length=1000, 
    enable_analyzer=True, # Whether to enable text analysis for this field
    enable_match=True # Whether to enable text match
)

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()
        .enableDynamicField(false)
        .build();

schema.addField(AddFieldReq.builder()
        .fieldName("text")
        .dataType(DataType.VarChar)
        .maxLength(1000)
        .enableAnalyzer(true)
        .enableMatch(true)
        .build());

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,
  },
];

export schema='{
        "autoId": true,
        "enabledDynamicField": false,
        "fields": [
            {
                "fieldName": "id",
                "dataType": "Int64",
                "isPrimary": true
            },
            {
                "fieldName": "text",
                "dataType": "VarChar",
                "elementTypeParams": {
                    "max_length": 1000,
                    "enable_analyzer": true,
                    "enable_match": true
                }
            },
            {
                "fieldName": "sparse",
                "dataType": "SparseFloatVector"
            }
        ]
    }'

可選:設定分析器

文字匹配的效能與精確度取決於所選擇的分析器。不同的分析器是針對各種語言和文字結構量身打造的,因此選擇正確的分析器可以顯著影響您特定使用個案的搜尋結果。

預設情況下,Milvus 使用standard 分析器,它會根據空白和標點符號來標記文字,移除長於 40 個字元的標記,並將文字轉換為小寫。應用此預設設定不需要額外參數。如需詳細資訊,請參閱標準

在需要不同分析器的情況下,您可以使用analyzer_params 參數設定一個分析器。例如,應用english 分析器來處理英文文字。

analyzer_params={
    "type": "english"
}

schema.add_field(
    field_name='text', 
    datatype=DataType.VARCHAR, 
    max_length=200, 
    enable_analyzer=True,
    analyzer_params=analyzer_params,
    enable_match=True, 
)

Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("type", "english");
schema.addField(AddFieldReq.builder()
        .fieldName("text")
        .dataType(DataType.VarChar)
        .maxLength(200)
        .enableAnalyzer(true)
        .analyzerParams(analyzerParams)
        .enableMatch(true)
        .build());

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,
    analyzer_params: { type: 'english' },
  },
  {
    name: "sparse",
    data_type: DataType.SparseFloatVector,
  },
];

export schema='{
        "autoId": true,
        "enabledDynamicField": false,
        "fields": [
            {
                "fieldName": "id",
                "dataType": "Int64",
                "isPrimary": true
            },
            {
                "fieldName": "text",
                "dataType": "VarChar",
                "elementTypeParams": {
                    "max_length": 200,
                    "enable_analyzer": true,
                    "enable_match": true,
                    "analyzer_params": {"type": "english"}
                }
            },
            {
                "fieldName": "my_vector",
                "dataType": "FloatVector",
                "elementTypeParams": {
                    "dim": "5"
                }
            }
        ]
    }'

Milvus 也提供其他各種適合不同語言和情境的分析器。如需詳細資訊,請參閱概述

使用文字匹配

一旦您在收集模式中啟用了 VARCHAR 欄位的文字匹配,您可以使用TEXT_MATCH 表達式執行文字匹配。

TEXT_MATCH 表達式語法

TEXT_MATCH 表達式用來指定欄位和要搜尋的詞彙。其語法如下。

TEXT_MATCH(field_name, text)

  • field_name:要搜尋的 VARCHAR 欄位名稱。

  • text:要搜尋的詞彙。根據語言和設定的分析器,多個詞彙可以用空格或其他適當的分隔符分隔。

預設情況下,TEXT_MATCH 使用OR匹配邏輯,這表示它會返回包含任何指定詞彙的文件。例如,若要搜尋text 欄位中包含machinedeep 詞彙的文件,請使用下列表達式。

filter = "TEXT_MATCH(text, 'machine deep')"
String filter = "TEXT_MATCH(text, 'machine deep')";
const filter = "TEXT_MATCH(text, 'machine deep')";
export filter="\"TEXT_MATCH(text, 'machine deep')\""

您也可以使用邏輯運算符結合多個TEXT_MATCH 表達式來執行AND匹配。

  • 若要搜尋text 欄位中同時包含machinedeep 的文件,請使用下列表達式。

    filter = "TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'deep')"
    
    String filter = "TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'deep')";
    
    const filter = "TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'deep')"
    
    export filter="\"TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'deep')\""
    
  • 若要搜尋text 欄位中同時包含machinelearning 但不包含deep 的文件,請使用下列表達式:

    filter = "not TEXT_MATCH(text, 'deep') and TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'learning')"
    
    String filter = "not TEXT_MATCH(text, 'deep') and TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'learning')";
    
    const filter = "not TEXT_MATCH(text, 'deep') and TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'learning')";
    
    export filter="\"not TEXT_MATCH(text, 'deep') and TEXT_MATCH(text, 'machine') and TEXT_MATCH(text, 'learning')\""
    

使用文字匹配進行搜尋

文字匹配可與向量相似性搜尋結合使用,以縮窄搜尋範圍並提昇搜尋效能。在向量類似性搜尋之前,先使用文字匹配篩選集合,就可以減少需要搜尋的文件數量,進而加快查詢時間。

在本範例中,filter 表達式過濾搜尋結果,使其只包含符合指定詞彙keyword1keyword2 的文件。然後,向量類似性搜尋就會在這個經過過濾的文件子集中執行。

# Match entities with `keyword1` or `keyword2`
filter = "TEXT_MATCH(text, 'keyword1 keyword2')"

# Assuming 'embeddings' is the vector field and 'text' is the VARCHAR field
result = MilvusClient.search(
    collection_name="YOUR_COLLECTION_NAME", # Your collection name
    anns_field="embeddings", # Vector field name
    data=[query_vector], # Query vector
    filter=filter,
    search_params={"params": {"nprobe": 10}},
    limit=10, # Max. number of results to return
    output_fields=["id", "text"] # Fields to return
)

String filter = "TEXT_MATCH(text, 'keyword1 keyword2')";

SearchResp searchResp = client.search(SearchReq.builder()
        .collectionName("YOUR_COLLECTION_NAME")
        .annsField("embeddings")
        .data(Collections.singletonList(queryVector)))
        .filter(filter)
        .topK(10)
        .outputFields(Arrays.asList("id", "text"))
        .build());
// Match entities with `keyword1` or `keyword2`
const filter = "TEXT_MATCH(text, 'keyword1 keyword2')";

// Assuming 'embeddings' is the vector field and 'text' is the VARCHAR field
const result = await client.search(
    collection_name: "YOUR_COLLECTION_NAME", // Your collection name
    anns_field: "embeddings", // Vector field name
    data: [query_vector], // Query vector
    filter: filter,
    params: {"nprobe": 10},
    limit: 10, // Max. number of results to return
    output_fields: ["id", "text"] //Fields to return
);
export filter="\"TEXT_MATCH(text, 'keyword1 keyword2')\""

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

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/search" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
    "collectionName": "demo2",
    "annsField": "my_vector",
    "data": [[0.19886812562848388, 0.06023560599112088, 0.6976963061752597, 0.2614474506242501, 0.838729485096104]],
    "filter": '"$filter"',
    "searchParams": {
        "params": {
            "nprobe": 10
        }
    },
    "limit": 3,
    "outputFields": ["text","id"]
}'

使用文字匹配進行查詢

文字匹配也可以用於查詢操作中的標量篩選。只要在query() 方法的expr 參數中指定TEXT_MATCH 表達式,就可以擷取與指定詞彙相符的文件。

下面的示例擷取text 欄位包含keyword1keyword2 兩個詞彙的文件。

# Match entities with both `keyword1` and `keyword2`
filter = "TEXT_MATCH(text, 'keyword1') and TEXT_MATCH(text, 'keyword2')"

result = MilvusClient.query(
    collection_name="YOUR_COLLECTION_NAME",
    filter=filter, 
    output_fields=["id", "text"]
)

String filter = "TEXT_MATCH(text, 'keyword1') and TEXT_MATCH(text, 'keyword2')";

QueryResp queryResp = client.query(QueryReq.builder()
        .collectionName("YOUR_COLLECTION_NAME")
        .filter(filter)
        .outputFields(Arrays.asList("id", "text"))
        .build()
);
// Match entities with both `keyword1` and `keyword2`
const filter = "TEXT_MATCH(text, 'keyword1') and TEXT_MATCH(text, 'keyword2')";

const result = await client.query(
    collection_name: "YOUR_COLLECTION_NAME",
    filter: filter, 
    output_fields: ["id", "text"]
)
export filter="\"TEXT_MATCH(text, 'keyword1') and TEXT_MATCH(text, 'keyword2')\""

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

curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/entities/query" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
-d '{
    "collectionName": "demo2",
    "filter": '"$filter"',
    "outputFields": ["id", "text"]
}'

注意事項

  • 為欄位啟用文字匹配會觸發建立反向索引,這會消耗儲存資源。在決定啟用此功能時,請考慮對儲存的影響,因為它會因文字大小、獨特標記和使用的分析器而異。

  • 一旦您在模式中定義了分析器,其設定就會永久適用於該集合。如果您認為不同的分析器更符合您的需求,您可以考慮刪除現有的集合,然後以所需的分析器設定建立新的集合。

  • filter 表達式中的 Escape 規則:

    • 在表達式中以雙引號或單引號括住的字元會被解釋為字串常數。如果字串常數包含轉換字元,則必須使用轉換順序來表示轉換字元。例如,使用\\ 表示\ ,使用\\t 表示制表符\t ,使用\\n 表示換行符。
    • 如果字串常數由單引號括住,常數內的單引號應表示為\\' ,而雙引號可表示為"\\" 。 例如:'It\\'s milvus'
    • 如果字串常數由雙引號括住,常數中的雙引號應表示為\\" ,而單引號可表示為'\\' 。 例:"He said \\"Hi\\""

免費嘗試托管的 Milvus

Zilliz Cloud 無縫接入,由 Milvus 提供動力,速度提升 10 倍。

開始使用
反饋

這個頁面有幫助嗎?