Inglese

L'analizzatore " english " di Milvus è progettato per elaborare testi in inglese, applicando regole specifiche della lingua per la tokenizzazione e il filtraggio.

Definizione

L'analizzatore english utilizza i seguenti componenti:

  • Tokenizzatore: utilizza il tokenizzatore «standard » per suddividere il testo in singole unità lessicali.

  • Filtri: include diversi filtri per un'elaborazione completa del testo:

    • lowercase: Converte tutti i token in minuscolo, consentendo ricerche che non tengono conto delle maiuscole e minuscole.

    • stemmer: Riduce le parole alla loro forma radice per consentire una corrispondenza più ampia (ad es., “running” diventa “run”).

    • stop_words: Rimuove le parole vuote comuni dell’inglese per concentrarsi sui termini chiave nel testo.

La funzionalità dell’analizzatore english è equivalente alla seguente configurazione dell’analizzatore personalizzato:

analyzer_params = {
    "tokenizer": "standard",
    "filter": [
        "lowercase",
        {
            "type": "stemmer",
            "language": "english"
        },
        {
            "type": "stop",
            "stop_words": ["_english_"]
        }
    ]
}
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",
        Arrays.asList("lowercase",
                new HashMap<String, Object>() {{
                    put("type", "stemmer");
                    put("language", "english");
                }},
                new HashMap<String, Object>() {{
                    put("type", "stop");
                    put("stop_words", Collections.singletonList("_english_"));
                }}
        )
);
analyzerParams := map[string]any{"tokenizer": "standard",
        "filter": []any{"lowercase", map[string]any{
            "type":     "stemmer",
            "language": "english",
        }, map[string]any{
            "type":       "stop",
            "stop_words": []string{"_english_"},
        }}}
use serde_json::json;

let analyzer_params = json!({
    "tokenizer": "standard",
    "filter": [
        "lowercase",
        { "type": "stemmer", "language": "english" },
        { "type": "stop", "stop_words": ["_english_"] }
    ]
});
nlohmann::json analyzer_params = {
    {"tokenizer", "standard"},
    {"filter", {
        "lowercase",
        {{"type", "stemmer"}, {"language", "english"}},
        {{"type", "stop"}, {"stop_words", {"_english_"}}}
    }}
};
const analyzer_params = {
    "tokenizer": "standard",
    "filter": [
        "lowercase",
        { "type": "stemmer", "language": "english" },
        { "type": "stop", "stop_words": ["_english_"] }
    ]
};
using System.Collections.Generic;

var analyzerParams = new Dictionary<string, object>
{
    ["tokenizer"] = "standard",
    ["filter"] = new object[]
    {
        "lowercase",
        new Dictionary<string, object>
        {
            ["type"] = "stemmer",
            ["language"] = "english"
        },
        new Dictionary<string, object>
        {
            ["type"] = "stop",
            ["stop_words"] = new[] { "_english_" }
        }
    }
};
# restful
analyzerParams='{
  "tokenizer": "standard",
  "filter": [
    "lowercase",
    {
      "type": "stemmer",
      "language": "english"
    },
    {
      "type": "stop",
      "stop_words": [
        "_english_"
      ]
    }
  ]
}'

Configurazione

Per applicare l’analizzatore “ english ” a un campo, è sufficiente impostare ` type ` su ` english ` in ` analyzer_params` e includere i parametri opzionali secondo necessità.

analyzer_params = {
    "type": "english",
}
Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("type", "english");
analyzerParams := map[string]any{"type": "english"}
use serde_json::json;

let analyzer_params = json!({
    "type": "english"
});
nlohmann::json analyzer_params = {
    {"type", "english"}
};
const analyzer_params = {
    "type": "english",
};
var analyzerParams = new Dictionary<string, object>
{
    ["type"] = "english"
};
# restful
analyzerParams='{
  "type": "english"
}'

L'analizzatore english accetta i seguenti parametri opzionali:

Parametro

Descrizione

stop_words

Un array contenente un elenco di parole di stop, che verranno rimosse dalla tokenizzazione. Il valore predefinito è _english_, un insieme integrato di parole di stop comuni in inglese.

Esempio di configurazione con parole vuote personalizzate:

analyzer_params = {
    "type": "english",
    "stop_words": ["a", "an", "the"]
}
Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("type", "english");
analyzerParams.put("stop_words", Arrays.asList("a", "an", "the"));
analyzerParams := map[string]any{"type": "english", "stop_words": []string{"a", "an", "the"}}
use serde_json::json;

let analyzer_params = json!({
    "type": "english",
    "stop_words": ["a", "an", "the"]
});
nlohmann::json analyzer_params = {
    {"type", "english"},
    {"stop_words", {"a", "an", "the"}}
};
const analyzer_params = {
    "type": "english",
    "stop_words": ["a", "an", "the"]
};
var analyzerParams = new Dictionary<string, object>
{
    ["type"] = "english",
    ["stop_words"] = new[] { "a", "an", "the" }
};
# restful
analyzerParams='{
  "type": "english",
  "stop_words": [
    "a",
    "an",
    "the"
  ]
}'

Dopo aver definito analyzer_params, è possibile applicarle a un campo VARCHAR durante la definizione dello schema di una collezione. Ciò consente a Milvus di elaborare il testo in quel campo utilizzando l'analizzatore specificato per una tokenizzazione e un filtraggio efficienti. Per ulteriori dettagli, consultare Esempio di utilizzo.

Esempi

Prima di applicare la configurazione dell’analizzatore allo schema della collezione, verificarne il comportamento utilizzando il metodo ` run_analyzer `.

Configurazione dell’analizzatore

analyzer_params = {
    "type": "english", # Uses the default `_english_` stop-word list
}
Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("type", "english");
analyzerParams := map[string]any{"type": "english"}
use serde_json::json;

let analyzer_params = json!({
    "type": "english"
});
nlohmann::json analyzer_params = {
    {"type", "english"}
};
const analyzer_params = {
    "type": "english", // Uses the default `_english_` stop-word list
};
var analyzerParams = new Dictionary<string, object>
{
    ["type"] = "english" // Uses the default `_english_` stop-word list
};
# restful
analyzerParams='{
  "type": "english"
}'

Verifica tramite run_analyzer

from pymilvus import (
    MilvusClient,
)

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

# Sample text to analyze
sample_text = "Milvus is a vector database built for scale!"

# Run the english analyzer with the defined configuration
result = client.run_analyzer(sample_text, analyzer_params)
print("English analyzer output:", result)
import java.util.*;
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;

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

List<String> texts = new ArrayList<>();
texts.add("Milvus is a vector database built for scale!");

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

for (RunAnalyzerResp.AnalyzerResult result : results) {
    for (RunAnalyzerResp.AnalyzerToken token : result.getTokens()) {
        System.out.println("English analyzer output: " + token.getToken());
    }
}
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{"Milvus is a vector database built for scale!"}
option := milvusclient.NewRunAnalyzerOption(texts...).
    WithAnalyzerParams(analyzerParams)

result, err := client.RunAnalyzer(ctx, option)
if err != nil {
    fmt.Println(err.Error())
    // handle error
}

for _, r := range result {
    for _, token := range r.Tokens {
        fmt.Println("English analyzer output:", token.Text)
    }
}
use milvus::v2::prelude::*;

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

let response = client
    .run_analyzer(
        RunAnalyzerRequest::builder()
            .texts(["Milvus is a vector database built for scale!"])
            .analyzer_params(analyzer_params)
            .build()?,
    )
    .await?;

for result in response.results() {
    for token in result.get_tokens() {
        println!("English analyzer output: {}", token.get_text());
    }
}
#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 = "Milvus is a vector database built for scale!";
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;
}

for (const auto& result : response.Results()) {
    for (const auto& token : result.Tokens()) {
        std::cout << "English analyzer output: " << token.token_ << std::endl;
    }
}
import { MilvusClient } from '@zilliz/milvus2-sdk-node';

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

const sample_text = 'Milvus is a vector database built for scale!';
const result = await client.runAnalyzer({
  text: sample_text,
  analyzer_params,
});
const tokens = result.results.flatMap(r => r.tokens.map(t => t.token));
console.log('English analyzer output:', tokens);
using Milvus.Client.V2;
using Milvus.Client.V2.Requests.Utility;
using Milvus.Client.V2.Responses.Utility;
using Milvus.Client.V2.Types;

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

// Sample text to analyze
var sampleText = "Milvus is a vector database built for scale!";

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

foreach (AnalyzerResult r in result.Results)
{
    foreach (AnalyzerToken t in r.Tokens)
    {
        Console.WriteLine($"English analyzer output: {t.Token}");
    }
}
curl --request POST \
  --url "http://localhost:19530/v2/vectordb/common/run_analyzer" \
  --header "Authorization: Bearer root:Milvus" \
  --header "Content-Type: application/json" \
  --data-raw '{
    "analyzerParams": "{\"type\": \"english\"}",
    "text": ["Milvus is a vector database built for scale!"]
  }'

Risultato atteso

Per il testo di esempio, l'analizzatore produce i seguenti token in ordine. Gli oggetti di risposta dell'SDK e la formattazione visualizzata variano a seconda del linguaggio; la risposta REST contiene questi token all'indirizzo data.results[].tokens[].token.

['milvus', 'vector', 'databas', 'built', 'scale']

Tradotto daDeepL

Prova Milvus gestito gratuitamente

Zilliz Cloud è senza problemi, basato su Milvus e 10 volte più veloce.

Inizia
Feedback

Questa pagina è stata utile?