跳到主要内容

Jieba

Jieba 分词器通过将中文文本拆分为其组成的单词来处理文本。

📘说明

jieba 分词器在输出的分词结果中会将标点符号作为独立的词元予以保留。例如:"你好!世界。" 的分词结果为 ["你好", "!", "世界", "。"]。如果需要在分词结果中去除标点符号词元,需要使用 removepunct 过滤器。

配置

在 Milvus 中,jieba 分词器有两种使用方法:一种为简单配置;另一种为自定义配置。

简单配置

使用简单配置时,您只需要将 tokenizer 设置为 "jieba"。例如

# Simple configuration: only specifying the tokenizer name
analyzer_params = {
"tokenizer": "jieba", # Use the default settings: dict=["_default_"], mode="search", hmm=True
}

上述简单配置与下方示例中的配置等效。

# Custom configuration equivalent to the simple configuration above
analyzer_params = {
"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
}

关于 Analyzer 参数的更多配置,可以参考自定义配置

自定义配置

为了更好地控制 Analyzer 参数,您可以自定义相关参数。例如,您可以参考如下示例为 Analyzer 提供自定义字典、选择文本切分方式,并选择是否开启隐式马尔科夫模型(HMM)等。

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

参数名称

参数描述

默认值

type

分词器类型,在使用 jieba 分词器时,该值为 jieba

"jieba"

dict

Analyzer 在分析文本时可以参考的词汇表,以字典的形式提供。内置的字典包括:

  • "default": 加载文本分析引擎内置的简单中文字典。更多详情,可以参考 dict.txt

  • "extend_default": 加载上述简单中文字典以及繁体中文的相关内容。更多详情,可以参考 dict.txt.big

    您也可以在引用内置字典的同时,添加任意长度的自定义字典。例如 ["default", "结巴分词器"]

["default"]

mode

文本切分方式。取值范围如下:

  • "exact": 尝试以最精确的方式对句子进行分段,使其满足文本分析的要求。

  • "search": 在 exact 模式的基础上,对长词进行切分以便提升召回率。适用于搜索引擎场景下的分词操作。

    更多详情,可参考 Jieba GitHub 项目

"search"

hmm

布尔型参数,指定是否开启隐式马尔科夫。当开启时,会对字典中未定义的单词进行可能地切分。

true

在定义了 analyzer_params 后,您可以在定义 Collection Schema 时将其应用到 VARCHAR 类型的字段上。Zilliz Cloud 将会根据 Analyzer 的设置对该字段的内容进行分词和过滤。更多详情,可参考使用示例

使用示例

在完成 Analyzer 配置后,您可以使用 run_analyzer 方法来验证分词效果是否符合预期。

Analyzer 配置

analyzer_params = {
"tokenizer": {
"type": "jieba",
"dict": ["结巴分词器"],
"mode": "exact",
"hmm": False
}
}

使用 run_analyzer 验证效果

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)

预期结果

['milvus', '结巴分词器', '中', '文', '测', '试']