Стоп

Фильтр « stop » удаляет указанные стоп-слова из токенизированного текста, помогая исключить распространенные, малозначимые слова. Список стоп-слов можно настроить с помощью параметра « stop_words ».

Настройка

Фильтр « stop » принимает список стоп-слов либо непосредственно через параметр ` stop_words `, либо из зарегистрированного файлового ресурса через параметр ` stop_words_file `.

Список стоп-слов, указанный непосредственно в конфигурации

Чтобы использовать фильтр stop со встроенным списком, укажите "type": "stop" в конфигурации фильтра вместе с параметром stop_words, содержащим список стоп-слов.

analyzer_params = {
    "tokenizer": "standard",
    "filter":[{
        "type": "stop", # Specifies the filter type as stop
        "stop_words": ["of", "to", "_english_"], # Defines custom stop words and includes the English stop word list
    }],
}
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("tokenizer", "standard");
analyzerParams.put("filter",
        Collections.singletonList(
                new HashMap<String, Object>() {{
                    put("type", "stop");
                    put("stop_words", Arrays.asList("of", "to", "_english_"));
                }}
        )
);
analyzerParams := map[string]any{"tokenizer": "standard",
    "filter": []any{map[string]any{
        "type":       "stop",
        "stop_words": []string{"of", "to", "_english_"},
    }}}
use milvus::v2::prelude::*;
use serde_json::json;

let analyzer_params = json!({
    "tokenizer": "standard",
    "filter": [{
        "type": "stop",
        "stop_words": ["of", "to", "_english_"]
    }]
});
nlohmann::json analyzer_params = {
    {"tokenizer", "standard"},
    {"filter", {
        {{"type", "stop"}, {"stop_words", {"of", "to", "_english_"}}}
    }}
};
const analyzer_params = {
    tokenizer: "standard",
    filter: [{
        type: "stop",  // Specifies the filter type as stop
        stop_words: ["of", "to", "_english_"],  // Custom stop words + built-in English list
    }],
};
using System.Collections.Generic;

Dictionary<string, object> analyzerParams = new()
{
    ["tokenizer"] = "standard",
    ["filter"] = new List<object>
    {
        new Dictionary<string, object>
        {
            ["type"] = "stop", // Specifies the filter type as stop
            ["stop_words"] = new List<object> { "of", "to", "_english_" } // Defines custom stop words and includes the English stop word list
        }
    }
};
# restful
analyzerParams='{
  "tokenizer": "standard",
  "filter": [
    {
      "type": "stop",
      "stop_words": [
        "of",
        "to",
        "_english_"
      ]
    }
  ]
}'

Фильтр stop поддерживает следующие настраиваемые параметры.

Параметр

Описание

stop_words

Список слов, которые следует исключить из токенизации. По умолчанию фильтр использует встроенный словарь « _english_ ». Его можно переопределить или расширить тремя способами:

  • Встроенные словари — укажите один из следующих языковых псевдонимов, чтобы использовать предопределенный словарь:

    "_arabic_", "_english_", "_danish_", "_dutch_", "_finnish_", "_french_", "_german_", "_hungarian_", "_italian_", "_norwegian_", "_portuguese_", "_russian_", "_spanish_", "_swedish_", "_thai_"

  • Пользовательский список — передайте массив собственных терминов, например, ["foo", "bar", "baz"].

  • Смешанный список — сочетание псевдонимов и пользовательских терминов, например: ["of", "to", "_english_"].

    Подробности о точном содержании каждого предопределённого словаря см. в разделе stop_words. Чтобы ознакомиться с арабским или тайским словарём, см. список стоп-слов на арабском языке или список стоп-слов на тайском языке.

Фильтр « stop » работает с терминами, сгенерированными токенизатором, поэтому его необходимо использовать в сочетании с токенизатором. Список токенизаторов, доступных в Milvus, см. на странице «Стандартный токенизатор» и связанных с ней страницах.

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

Загрузка стоп-слов из файлового ресурсаCompatible with Milvus 3.0.x

Для больших пользовательских списков стоп-слов — языковых списков, словарей конкретных областей знаний или списков, которые вы хотите использовать во многих коллекциях — сохраните слова в файле и зарегистрируйте файл в качестве удалённого файлового ресурса, а затем укажите на него в фильтре с помощью параметра « stop_words_file ». Параметр ` stop_words_file ` можно использовать как отдельно, так и вместе со встроенным параметром ` stop_words`; если оба параметра заданы, фильтр объединяет эти два источника в единый список стоп-слов.

Файл представляет собой обычный текст в кодировке UTF‑8, в котором каждое стоп-слово занимает отдельную строку. Например:

the
of
for

Загрузите файл в хранилище объектов, на использование которого настроен ваш кластер Milvus, а затем зарегистрируйте его:

from pymilvus import MilvusClient

client = MilvusClient(uri="http://localhost:19530")

# Register the uploaded file under a name you'll reference from analyzer configs.
client.add_file_resource(
    name="en_stop_words",
    path="file/stop_words.txt",    # full S3 object key, including the rootPath prefix
)

Ссылайтесь на зарегистрированный ресурс в фильтре с помощью stop_words_file:

analyzer_params = {
    "tokenizer": "standard",
    "filter": [{
        "type": "stop",
        "stop_words_file": {
            "type": "remote",
            "resource_name": "en_stop_words",
            "file_name": "stop_words.txt",
        },
    }],
}

Параметр ` stop_words_file ` принимает объект со следующими полями:

Поле

Описание

type

Тип ресурса. Используйте "remote" для файла, зарегистрированного с помощью add_file_resource. Для варианта "local", используемого в самохостируемых развертываниях, см. раздел «Управление файловыми ресурсами».

resource_name

Имя, использованное при регистрации файла на сайте add_file_resource.

file_name

Часть пути к хранилищу объектов зарегистрированного ресурса, соответствующая имени файла (например, "stop_words.txt", если ресурс был зарегистрирован на сайте path="file/stop_words.txt").

Примеры

Прежде чем применить конфигурацию анализатора к схеме вашей коллекции, проверьте его поведение с помощью метода run_analyzer.

Конфигурация анализатора

analyzer_params = {
    "tokenizer": "standard",
    "filter":[{
        "type": "stop", # Specifies the filter type as stop
        "stop_words": ["of", "to", "_english_"], # Defines custom stop words and includes the English stop word list
    }],
}
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("tokenizer", "standard");
analyzerParams.put("filter",
        Collections.singletonList(
                new HashMap<String, Object>() {{
                    put("type", "stop");
                    put("stop_words", Arrays.asList("of", "to", "_english_"));
                }}
        )
);
analyzerParams := map[string]any{"tokenizer": "standard",
    "filter": []any{map[string]any{
        "type":       "stop",
        "stop_words": []string{"of", "to", "_english_"},
    }}}
use milvus::v2::prelude::*;
use serde_json::json;

let analyzer_params = json!({
    "tokenizer": "standard",
    "filter": [{
        "type": "stop",
        "stop_words": ["of", "to", "_english_"]
    }]
});
nlohmann::json analyzer_params = {
    {"tokenizer", "standard"},
    {"filter", {
        {{"type", "stop"}, {"stop_words", {"of", "to", "_english_"}}}
    }}
};
const analyzer_params = {
    tokenizer: "standard",
    filter: [{
        type: "stop",  // Specifies the filter type as stop
        stop_words: ["of", "to", "_english_"],  // Custom stop words + built-in English list
    }],
};
using System.Collections.Generic;

Dictionary<string, object> analyzerParams = new()
{
    ["tokenizer"] = "standard",
    ["filter"] = new List<object>
    {
        new Dictionary<string, object>
        {
            ["type"] = "stop", // Specifies the filter type as stop
            ["stop_words"] = new List<object> { "of", "to", "_english_" } // Defines custom stop words and includes the English stop word list
        }
    }
};
# restful
analyzerParams='{
  "tokenizer": "standard",
  "filter": [
    {
      "type": "stop",
      "stop_words": [
        "of",
        "to",
        "_english_"
      ]
    }
  ]
}'

Проверка с помощью run_analyzer

from pymilvus import (
    MilvusClient,
)

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

# Sample text to analyze
sample_text = "The stop filter allows control over common stop words for text processing."

# Run the analyzer with the defined configuration
result = client.run_analyzer(sample_text, analyzer_params)
print("Analyzer output:", result)
import io.milvus.v2.client.ConnectConfig;
import io.milvus.v2.client.MilvusClientV2;
import io.milvus.v2.service.vector.request.RunAnalyzerReq;
import io.milvus.v2.service.vector.response.RunAnalyzerResp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

ConnectConfig config = ConnectConfig.builder()
        .uri("http://localhost:19530")
        .token("root:Milvus")
        .build();
MilvusClientV2 client = new MilvusClientV2(config);

List<String> texts = new ArrayList<>();
texts.add("The stop filter allows control over common stop words for text processing.");

RunAnalyzerResp resp = client.runAnalyzer(RunAnalyzerReq.builder()
        .texts(texts)
        .analyzerParams(analyzerParams)
        .build());
List<RunAnalyzerResp.AnalyzerResult> results = resp.getResults();
import (
    "context"
    "fmt"

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

ctx := context.Background()

client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
    Address: "http://localhost:19530",
    APIKey:  "root:Milvus",
})
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

texts := []string{"The stop filter allows control over common stop words for text processing."}
option := milvusclient.NewRunAnalyzerOption(texts...).
    WithAnalyzerParams(analyzerParams)

result, err := client.RunAnalyzer(ctx, option)
if err != nil {
    fmt.Println(err.Error())
    // handle error
}
fmt.Println(result)
use milvus::v2::prelude::*;
use serde_json::json;

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

let analyzer_params = json!({
    "tokenizer": "standard",
    "filter": [{
        "type": "stop",
        "stop_words": ["of", "to", "_english_"]
    }]
});
let result = client
    .run_analyzer(
        RunAnalyzerRequest::builder()
            .texts(vec!["The stop filter allows control over common stop words for text processing."])
            .analyzer_params(analyzer_params)
            .build()?,
    )
    .await?;
#include "milvus/MilvusClientV2.h"
#include <iostream>
#include <string>

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

std::string text = "The stop filter allows control over common stop words for text processing.";
auto request = milvus::RunAnalyzerRequest()
                       .AddText(text)
                       .WithAnalyzerParams(analyzer_params);

milvus::RunAnalyzerResponse response;
status = client->RunAnalyzer(request, response);
if (!status.IsOk()) {
    std::cout << status.Message() << std::endl;
}
import { MilvusClient } from "@zilliz/milvus2-sdk-node";

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

const sample_text = "The stop filter allows control over common stop words for text processing.";

// Run the analyzer with the defined configuration
const result = await client.runAnalyzer({
    text: sample_text,
    analyzer_params,
});
console.log("Analyzer output:", result);
using Milvus.Client.V2;
using Milvus.Client.V2.Requests.Utility;
using Milvus.Client.V2.Responses.Utility;
using Milvus.Client.V2.Types;

MilvusClientV2 client = new(new ConnectConfig
{
    Uri = "http://localhost:19530",
    ApiKey = "root:Milvus"
});

// Sample text to analyze
string sampleText = "The stop filter allows control over common stop words for text processing.";

// Run the analyzer with the defined configuration
RunAnalyzerResp result = await client.RunAnalyzerAsync(new RunAnalyzerReq
{
    AnalyzerParams = analyzerParams,
    Texts = [sampleText]
});

foreach (AnalyzerToken t in result.Results.SelectMany(r => r.Tokens))
{
    Console.WriteLine(t.Token);
}
# restful
curl --request POST \
     --url "http://localhost:19530/v2/vectordb/common/run_analyzer" \
     --header "Authorization: Bearer root:Milvus" \
     --header "Content-Type: application/json" \
     -d '{
        "text": ["The stop filter allows control over common stop words for text processing."],
        "analyzerParams": "{\"tokenizer\": \"standard\", \"filter\": [{\"type\": \"stop\", \"stop_words\": [\"of\", \"to\", \"_english_\"]}]}"
     }'

Ожидаемый результат

['The', 'stop', 'filter', 'allows', 'control', 'over', 'common', 'stop', 'words', 'text', 'processing']

ПереведеноDeepL

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

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

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

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