Jieba
Jieba 分词器通过将中文文本拆分为其组成的单词来处理文本。
jieba 分词器在输出的分词结果中会将标点符号作为独立的词元予以保留。例如:"你好!世界。" 的分词结果为 ["你好", "!", "世界", "。"]。如果需要在分词结果中去除标点符号词元,需要使用 removepunct 过滤器。
配置
在 Milvus 中,jieba 分词器有两种使用方法:一种为简单配置;另一种为自定义配置。
简单配置
使用简单配置时,您只需要将 tokenizer 设置为 "jieba"。例如
- Python
- Java
- Go
- Rust
- C++
- NodeJS
- cURL
# Simple configuration: only specifying the tokenizer name
analyzer_params = {
"tokenizer": "jieba", # Use the default settings: dict=["_default_"], mode="search", hmm=True
}
Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("tokenizer", "jieba");
analyzerParams := map[string]any{"tokenizer": "jieba"}
use milvus::v2::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
let analyzer_params = serde_json::json!({"tokenizer": "jieba"});
Ok(())
}
nlohmann::json analyzer_params = {
{"tokenizer", "jieba"}
};
const analyzer_params = {
"tokenizer": "jieba",
};
# restful
analyzerParams='{
"tokenizer": "jieba"
}'
上述简单配置与下方示例中的配置等效。
- Python
- Java
- Go
- Rust
- C++
- NodeJS
- cURL
# Custom configuration equivalent to the simple configuration above
analyzer_params = {
"tokenizer": { # Tokenizer configuration
"type": "jieba", # Tokenizer type, fixed as "jieba"
"dict": ["_default_"], # Use the default dictionary
"mode": "search", # Use search mode for improved recall (see mode details below)
"hmm": True # Enable HMM for probabilistic segmentation
}
}
Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("tokenizer", new HashMap<String, Object>() {{
put("type", "jieba");
put("dict", Collections.singletonList("_default_"));
put("mode", "search");
put("hmm", true);
}});
analyzerParams := map[string]any{
"tokenizer": map[string]any{
"type": "jieba",
"dict": []any{"_default_"},
"mode": "search",
"hmm": true,
},
}
let analyzer_params = serde_json::json!({
"tokenizer": {
"type": "jieba",
"dict": ["_default_"],
"mode": "search",
"hmm": true
}
});
nlohmann::json analyzer_params = {
{"tokenizer", {
{"type", "jieba"},
{"dict", {"_default_"}},
{"mode", "search"},
{"hmm", true}
}}
};
const analyzer_params = {
tokenizer: {
type: "jieba",
dict: ["_default_"],
mode: "search",
hmm: true,
},
};
# restful
export analyzerParams='{
"tokenizer": {
"type": "jieba",
"dict": ["_default_"],
"mode": "search",
"hmm": true
}
}'
关于 Analyzer 参数的更多配置,可以参考自定义配置。
自定义配置
为了更好地控制 Analyzer 参数,您可以自定义相关参数。例如,您可以参考如下示例为 Analyzer 提供自定义字典、选择文本切分方式,并选择是否开启隐式马尔科夫模型(HMM)等。
- Python
- Java
- Go
- Rust
- C++
- NodeJS
- cURL
# Custom configuration with user-defined settings
analyzer_params = {
"tokenizer": {
"type": "jieba", # Fixed tokenizer type
"dict": ["customDictionary"], # Custom dictionary list; replace with your own terms
"mode": "exact", # Use exact mode (non-overlapping tokens)
"hmm": False # Disable HMM; unmatched text will be split into individual characters
}
}
Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("tokenizer", new HashMap<String, Object>() {{
put("type", "jieba");
put("dict", Arrays.asList("customDictionary"));
put("mode", "exact");
put("hmm", false);
}});
analyzerParams := map[string]interface{}{
"tokenizer": map[string]interface{}{
"type": "jieba",
"dict": []string{"customDictionary"},
"mode": "exact",
"hmm": false,
},
}
let analyzer_params = serde_json::json!({
"tokenizer": {
"type": "jieba",
"dict": ["customDictionary"],
"mode": "exact",
"hmm": false
}
});
nlohmann::json analyzerParams = {
{"tokenizer", {
{"type", "jieba"},
{"dict", {"customDictionary"}},
{"mode", "exact"},
{"hmm", false}
}}
};
const analyzer_params = {
tokenizer: {
type: "jieba",
dict: ["customDictionary"],
mode: "exact",
hmm: false,
},
};
# restful
export analyzerParams='{
"tokenizer": {
"type": "jieba",
"dict": ["customDictionary"],
"mode": "exact",
"hmm": false
}
}'
参数名称 | 参数描述 | 默认值 |
|---|---|---|
| 分词器类型,在使用 |
|
| Analyzer 在分析文本时可以参考的词汇表,以字典的形式提供。内置的字典包括:
您也可以在引用内置字典的同时,添加任意长度的自定义字典。例如 |
|
| 文本切分方式。取值范围如下:
更多详情,可参考 Jieba GitHub 项目。 |
|
| 布尔型参数,指定是否开启隐式马尔科夫。当开启时,会对字典中未定义的单词进行可能地切分。 |
|
在定义了 analyzer_params 后,您可以在定义 Collection Schema 时将其应用到 VARCHAR 类型的字段上。Zilliz Cloud 将会根据 Analyzer 的设置对该字段的内容进行分词和过滤。更多详情,可参考使用示例。
使用示例
在完成 Analyzer 配置后,您可以使用 run_analyzer 方法来验证分词效果是否符合预期。
Analyzer 配置
- Python
- Java
- Go
- Rust
- C++
- NodeJS
- cURL
analyzer_params = {
"tokenizer": {
"type": "jieba",
"dict": ["结巴分词器"],
"mode": "exact",
"hmm": False
}
}
Map<String, Object> analyzerParams = new HashMap<>();
analyzerParams.put("tokenizer", new HashMap<String, Object>() {{
put("type", "jieba");
put("dict", Arrays.asList("结巴分词器"));
put("mode", "exact");
put("hmm", false);
}});
analyzerParams := map[string]interface{}{
"tokenizer": map[string]interface{}{
"type": "jieba",
"dict": []string{"结巴分词器"},
"mode": "exact",
"hmm": false,
},
}
let analyzer_params = serde_json::json!({
"tokenizer": {
"type": "jieba",
"dict": ["结巴分词器"],
"mode": "exact",
"hmm": false
}
});
nlohmann::json analyzerParams = {
{"tokenizer", {
{"type", "jieba"},
{"dict", {"结巴分词器"}},
{"mode", "exact"},
{"hmm", false}
}}
};
const analyzer_params = {
tokenizer: {
type: "jieba",
dict: ["结巴分词器"],
mode: "exact",
hmm: false,
},
};
# restful
export analyzerParams='{
"tokenizer": {
"type": "jieba",
"dict": ["结巴分词器"],
"mode": "exact",
"hmm": false
}
}'
使用 run_analyzer 验证效果
- Python
- Java
- Go
- Rust
- C++
- NodeJS
- cURL
from pymilvus import (
MilvusClient,
)
client = MilvusClient(
uri="YOUR_CLUSTER_ENDPOINT",
token="YOUR_CLUSTER_TOKEN"
)
# Sample text to analyze
sample_text = "milvus结巴分词器中文测试"
# Run the standard analyzer with the defined configuration
result = client.run_analyzer(sample_text, analyzer_params)
print("Standard 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;
ConnectConfig config = ConnectConfig.builder()
.uri("YOUR_CLUSTER_ENDPOINT")
.token("YOUR_CLUSTER_TOKEN")
.build();
MilvusClientV2 client = new MilvusClientV2(config);
List<String> texts = new ArrayList<>();
texts.add("milvus结巴分词器中文测试");
RunAnalyzerResp resp = client.runAnalyzer(RunAnalyzerReq.builder()
.texts(texts)
.analyzerParams(analyzerParams)
.build());
List<RunAnalyzerResp.AnalyzerResult> results = resp.getResults();
import (
"context"
"encoding/json"
"fmt"
"github.com/milvus-io/milvus/client/v3/milvusclient"
)
client, err := milvusclient.New(ctx, &milvusclient.ClientConfig{
Address: "YOUR_CLUSTER_ENDPOINT",
APIKey: "YOUR_CLUSTER_TOKEN",
})
if err != nil {
fmt.Println(err.Error())
// handle error
}
bs, _ := json.Marshal(analyzerParams)
texts := []string{"milvus结巴分词器中文测试"}
option := milvusclient.NewRunAnalyzerOption(texts).
WithAnalyzerParamsStr(string(bs))
result, err := client.RunAnalyzer(ctx, option)
if err != nil {
fmt.Println(err.Error())
// handle error
}
let resp = client.run_analyzer(RunAnalyzerRequest::builder()
.texts(vec!["milvus结巴分词器中文测试"])
.analyzer_params(analyzer_params)
.build()?).await?;
println!("{:?}", resp.results());
#include "milvus/MilvusClientV2.h"
auto client = milvus::MilvusClientV2::Create();
milvus::ConnectParam connect_param{"YOUR_CLUSTER_ENDPOINT", "YOUR_CLUSTER_TOKEN"};
auto status = client->Connect(connect_param);
if (!status.IsOk()) {
std::cout << status.Message() << std::endl;
}
std::string text = "milvus结巴分词器中文测试";
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;
}
const analyzer_params = {
tokenizer: {
type: "jieba",
dict: ["结巴分词器"],
mode: "exact",
hmm: false,
},
};
const result = await client.runAnalyzer({
text: "milvus结巴分词器中文测试",
analyzer_params,
});
console.log(result.results);
curl --request POST \
--url "${CLUSTER_ENDPOINT}/v2/vectordb/common/run" \
--header "Authorization: Bearer ${TOKEN}" \
--header "Content-Type: application/json" \
--data '{
"text": "milvus结巴分词器中文测试",
"analyzerParams": {
"tokenizer": {
"type": "jieba",
"dict": ["结巴分词器"],
"mode": "exact",
"hmm": false
}
}
}'
预期结果
['milvus', '结巴分词器', '中', '文', '测', '试']