Stop
O filtro « stop » remove as palavras de paragem especificadas do texto tokenizado, ajudando a eliminar palavras comuns e menos significativas. Pode configurar a lista de palavras de paragem utilizando o parâmetro « stop_words ».
Configuração
O filtro « stop » aceita a sua lista de palavras de paragem quer diretamente através do parâmetro « stop_words », quer a partir de um recurso de ficheiro registado através do parâmetro « stop_words_file ».
Lista de palavras de exclusão incorporada
Para utilizar o filtro stop com uma lista incorporada, especifique "type": "stop" na configuração do filtro, juntamente com um parâmetro stop_words que forneça a lista de palavras de exclusão.
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_"
]
}
]
}'
O filtro stop aceita os seguintes parâmetros configuráveis.
Parâmetro |
Descrição |
|---|---|
|
Uma lista de palavras a remover da tokenização. Por predefinição, o filtro utiliza o dicionário «
|
O filtro « stop » opera sobre os termos gerados pelo tokenizador, pelo que deve ser utilizado em combinação com um tokenizador. Para obter uma lista dos tokenizadores disponíveis no Milvus, consulte «Tokenizador Padrão» e as suas páginas relacionadas.
Após definir as palavras de exclusão ( analyzer_params), pode aplicá-las a um campo « VARCHAR » ao definir um esquema de coleção. Isto permite que o Milvus processe o texto nesse campo utilizando o analisador especificado para uma tokenização e filtragem eficientes. Para mais detalhes, consulte «Exemplo de utilização».
Carregar palavras de exclusão a partir de um recurso de ficheiroCompatible with Milvus 3.0.x
Para grandes listas personalizadas de palavras de paragem — listas específicas de cada idioma, vocabulários de domínio ou listas que pretenda partilhar entre várias coleções — guarde as palavras num ficheiro e registe o ficheiro como um recurso de ficheiro remoto; em seguida, faça referência a ele a partir do filtro através do parâmetro « stop_words_file ». Pode utilizar « stop_words_file » isoladamente ou em conjunto com « stop_words »; quando ambos estiverem definidos, o filtro combina as duas fontes numa única lista de palavras de paragem.
O ficheiro é texto simples em UTF‑8 com uma palavra de exclusão por linha. Por exemplo:
the
of
for
Carregue o ficheiro para o armazenamento de objetos que o seu cluster Milvus está configurado para utilizar e, em seguida, registe-o:
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
)
Faça referência ao recurso registado no filtro através de ` 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",
},
}],
}
O parâmetro ` stop_words_file ` aceita um objeto com os seguintes campos:
Campo |
Descrição |
|---|---|
|
O tipo de recurso. Utilize « |
|
O nome utilizado quando o ficheiro foi registado em |
|
A parte do nome do ficheiro do caminho do armazenamento de objetos do recurso registado (por exemplo, |
Exemplos
Antes de aplicar a configuração do analisador ao esquema da sua coleção, verifique o seu comportamento utilizando o método run_analyzer.
Configuração do analisador
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_"
]
}
]
}'
Verificação utilizando 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_\"]}]}"
}'
Resultado esperado
['The', 'stop', 'filter', 'allows', 'control', 'over', 'common', 'stop', 'words', 'text', 'processing']