Use the analysis-ansj plugin
The analysis-ansj plugin is a Chinese tokenizer for PolarSearch ported from elasticsearch-analysis-ansj. It is built on the ansj_seg algorithm, provides multiple tokenization modes, and supports custom dictionaries, including hot updates.
Overview
Its features and usage are identical to the original plugin, except that custom dictionaries and configuration files must be uploaded through the PolarSearch console.
This plugin is built on the ansj_seg tokenization algorithm. It provides multiple tokenization modes, supports user, stopword, synonym, and ambiguity dictionaries, and supports hot dictionary updates.
Key features include:
tokenizer: Splits continuous Chinese text into meaningful terms and controls the tokenization granularity.
Multiple dictionary types: Define the rules for token matching.
Hot update mechanism: Supports dynamic updates for configuration and dictionary files.
Tokenization rules
The analysis-ansj plugin provides the following five tokenization modes:
Name | Tokenization mode | Description | Use cases |
| index mode | Adds sub-word splitting to standard tokenization to generate more tokens and improve search recall. | Recommended for indexing. |
| query mode | Standard tokenization that generates fewer but more meaningful tokens to improve query precision. | Recommended for searching. |
| user dictionary mode | Prioritizes matching terms in the user dictionary. | For scenarios requiring forced recognition of specific terms. |
| base mode | The most basic tokenization method. | Scenarios where tokenization precision is not a high priority. |
| NLP mode | Based on a Conditional Random Field (CRF) model for the highest tokenization precision. | NLP scenarios that require high-quality tokenization. |
Dictionary types
The analysis-ansj plugin supports the following four types of custom dictionaries. You can load multiple dictionary files of the same type by adding a suffix to the configuration key, for example, dic_custom and dic_domain.
Dictionary type | Configuration key prefix | Description |
User dictionary |
| Stores custom, business-specific new terms. |
Stopword dictionary |
| Stores meaningless terms, such as |
Ambiguity dictionary |
| Resolves tokenization ambiguity by forcing a specific segmentation for certain text combinations. |
Synonym dictionary |
| Stores synonym mappings for automatic semantic expansion during tokenization. |
Applicable versions
PolarSearch version 3.0.1.1.1, 1.0.1.1.1, or later.
Dictionary file specifications
Before uploading a custom dictionary, ensure your file meets the following requirements. Otherwise, the dictionary may fail to upload, load, or function correctly.
Upload and naming limits
File size limit: A single file can be up to 10 MB.
File quantity limit: You can upload up to 10 custom dictionary files per application.
Filename conventions: The filename can contain only uppercase and lowercase letters, digits, and underscores (
_). The length must not exceed 30 characters, and the file extension must be.dic.Uniqueness requirement: Dictionary names must be unique within the current application. The name cannot be changed after the dictionary is added.
General content format specifications
File encoding: The file must be saved with UTF-8 encoding.
Line breaks: Each line must contain only one entry, ending with a newline character (
\n).
Type-specific format requirements
In addition to the general specifications, different Ansj dictionary types have specific internal formatting requirements:
User dictionary (dic)
Format:
term part_of_speech term_frequency. Fields must be separated by a tab character (\t). The part of speech and term frequency are optional parameters.Example:
阿里巴巴 nt 50000 人工智能 n 40000 机器学习 n 35000
Stopword dictionary (stop)
Format: Each line contains one stopword to be filtered.
Example:
的 了 和 是
Synonym dictionary (synonyms)
Format: Each line contains a set of synonyms. Terms must be separated by a tab character (
\t).Example:
人 士 人物 广播员 播音员 飞行员 航空员 试飞员Ambiguity dictionary (ambiguity)
Format:
term1\tpos1\tterm2\tpos2....Constraints:
Fields must be separated by a tab character (
\t).Each line must contain an even number of fields because terms and parts of speech must appear in pairs. Otherwise, the system skips the line, and it is not loaded.
Example:
上海 ns 市 n 长江大桥 nz
Dictionary management
The analysis-ansj plugin supports the following dictionary management operations: uploading, updating, and deleting dictionaries.
Upload Dictionary: While a dictionary is uploading, the Upload Dictionary button is grayed out. You can click the Refresh button during this process. When the Upload Dictionary button turns blue again, the upload is complete.
Update a dictionary: To update a dictionary, delete the old one and upload a new file with the same name. You must then call the API to refresh the dictionaries across the cluster for the changes to take effect.
ImportantUpdating a dictionary does not interrupt service. It only affects the tokenization of new data. Existing data is not re-tokenized with the new dictionary. This inconsistency between old and new tokenization logic might make some historical data unsearchable. We recommend using the old dictionary for existing indexes and the new dictionary for newly created indexes.
If you need to apply the latest dictionary to existing data, run the following command to update the index:
POST /your_index/_update_by_query. To avoid impacting your business, perform this operation during off-peak hours.Update the configuration file: You can update the configuration file by uploading
ansj.cfg.ymlin the console.Deletea dictionary: You can delete a dictionary if it is no longer needed.
ImportantDeleting a dictionary is irreversible, so proceed with caution. We recommend against deleting dictionaries unless necessary. Instead, update dictionary content to adjust your tokenization strategy.
If you must delete a dictionary and need to fix historical data, you can first update the dictionary and then run
POST /your_index/_update_by_queryto update the index documents and ensure consistent data tokenization.
Plugin configuration file
To ensure that newly uploaded dictionaries are correctly recognized and associated within the tokenizer, you must configure the ansj.cfg.yml file. This filename is fixed.
Create or modify a YAML configuration file named
ansj.cfg.ymlon your local machine. Configure global control parameters and dictionary mappings as needed.The standard format and description of a complete configuration file are as follows:
ansj: # ===== Global Parameter Configuration ===== isNameRecognition: true # Whether to enable Chinese name recognition isNumRecognition: true # Whether to enable number recognition isQuantifierRecognition: true # Whether to merge numbers and quantifiers (e.g., "三个") isRealName: false # Whether to keep original terms (recommended: false) # ===== Custom User Dictionaries ===== dic: custom.dic # user dictionary # dic_extra: my_dic.dic # Supports configuring multiple dictionaries with different keys # ===== Stopword Dictionary ===== # stop: my_stop.dic # ===== Ambiguity Dictionary ===== # ambiguity: my_ambiguity.dic # ===== Synonym Dictionary ===== # synonyms: my_synonyms.dicGlobal parameters
Parameter
Type
Default
Description
isNameRecognitionboolean
true
Enables Chinese name recognition.
isNumRecognitionboolean
true
Enables number recognition.
isQuantifierRecognitionboolean
true
Specifies whether to merge numbers and quantifiers.
isRealNameboolean
false
Specifies whether to keep the original term.
isSkipUserDefineboolean
false
Specifies whether to skip the user-defined dictionary.
Configure and use a custom analyzer
You can create a custom analyzer in your index settings and specify custom dictionary keys and parameters to use it. The custom dictionary keys must be specified in the configuration file, and the configuration must then be reloaded for the changes to take effect.
The following example uses the dic_key1 and dic_test1 user dictionaries, the stop_key1 stopword dictionary, the ambiguity_key2 ambiguity dictionary, and the synonyms_test1 synonym dictionary.
PUT /custom_index
{
"settings": {
"index": {
"analysis": {
"tokenizer": {
"my_ansj_tokenizer": {
"type": "dic_ansj",
"dic": "dic_key1,dic_test1",
"stop": "stop_key1",
"ambiguity": "ambiguity_key2",
"synonyms": "synonyms_test1",
"isNameRecognition": true,
"isNumRecognition": true,
"isQuantifierRecognition": true,
"isRealName": false
}
},
"analyzer": {
"my_ansj_analyzer": {
"type": "custom",
"tokenizer": "my_ansj_tokenizer"
}
}
}
}
},
"mappings": {
"properties": {
"content": {
"type": "text",
"analyzer": "my_ansj_analyzer"
}
}
}
}Custom tokenizer parameters
Parameter | Type | Description |
| string | Tokenizer type. Valid values: index_ansj, query_ansj, dic_ansj, base_ansj, nlp_ansj. |
| string | User dictionary key. Separate multiple keys with commas. |
| string | Stopword dictionary key. Separate multiple keys with commas. |
| string | Ambiguity dictionary key. |
| string | Synonym dictionary key. Separate multiple keys with commas. |
Update Ansj dictionaries
The analysis-ansj plugin supports hot dictionary updates, which do not require restarting the cluster.
Procedure
Upload the new dictionary file to the appropriate category.
If you added a new dictionary, modify the
ansj.cfg.ymlfile to add the dictionary key, upload the configuration file, and then call the API to refresh the configuration.Call the API to refresh the dictionary.
Refresh dictionaries across the cluster
Request:
GET /_ansj/flush/dic?key=dicParameters:
Key
Description
dicRefreshes the default user dictionary.
dic_<custom_name>Refreshes the user dictionary with the specified name.
stopRefreshes the default stopword dictionary.
stop_<custom_name>Refreshes the stopword dictionary with the specified name.
ambiguityRefreshes the default ambiguity dictionary.
ambiguity_<custom_name>Refreshes the ambiguity dictionary with the specified name.
synonymsRefreshes the default synonym dictionary.
synonyms_<custom_name>Refreshes the synonym dictionary with the specified name.
Example response:
{ "10.0.0.1:9300": "success", "10.0.0.2:9300": "success", "10.0.0.3:9300": "success" }
Refresh configuration
GET /_ansj/flush/config
Refreshing the configuration reloads all dictionaries, which may consume system resources. We recommend performing this operation during off-peak hours.
Impacts of updating Ansj dictionaries
Risk of inconsistent tokenization and unsearchable existing data:
Newly indexed data: After a dictionary change, newly indexed documents will use the updated tokenization rules.
Existing data: The analysis results for existing documents are not updated automatically. This discrepancy between old and new tokenization logic may prevent you from retrieving existing data with new keywords.
Solution: If you must apply the latest dictionary to existing data, run the following update command during off-peak hours:
POST /your_index/_update_by_query
Decreased recall: If you delete an existing entry from the dictionary, such as
machine learning, the term is split intomachineandlearningduring word segmentation. This prevents results that require an exact match from being recalled.Decreased precision (increased noise): If a stop word dictionary is deleted or disabled, meaningless words that were originally filtered, such as
的and啊, will be included in indexing and retrieval again, interfering with search results.Deviations in relevance scores (TF/IDF): Dictionary changes alter tokenization statistics like term frequency (TF) and inverse document frequency (IDF). This can cause fluctuations in the relevance ranking of search results.
Operational caution: Deleting or disabling dictionaries is a high-risk operation. We recommend updating a dictionary's content by uploading a new file with the same name. This approach provides a smoother way to adjust your analysis strategy.
Quick validation and testing
Classic scenario example
Step 1: Create a basic test index. Use
index_ansjduring indexing for fine-grained tokenization to improve recall, and usequery_ansjduring search for coarse-grained tokenization to ensure precision.PUT /test_index?pretty { "settings" : { "index" : { "number_of_shards" : 16, "number_of_replicas" : 1, "refresh_interval":"5s" } }, "mappings" : { "properties" : { "test_field": { "type": "text", "analyzer": "index_ansj", "search_analyzer": "query_ansj" } } } }Step 2: Test the validity of the analyzer configuration.
POST /test_index/_analyze { "field": "test_field", "text": "中国" }Step 3: Add test data in bulk.
PUT test_index/_bulk?refresh {"create":{ }} { "test_field" : "中国" } {"create":{ }} { "test_field" : "中华人民共和国" } {"create":{ }} { "test_field" : "中国有56个民族" } {"create":{ }} { "test_field" : "中国是社会主义国家" }Step 4: Perform a search to verify the results.
GET test_index/_search { "query": { "match": { "test_field": { "query": "中国" } } } }
Validate dictionaries by using the API
You can use the dedicated test API provided by the Ansj plugin to quickly diagnose the analysis pipeline by specifying a tokenizer and specific dictionary keys:
GET /_cat/ansj?text=中华人民共和国&type=index_ansj&dic=dic_d1Example response:
{ "result": [ { "name": "中华人民共和国", "nature": "ns", "offe": 0, "realName": "中华人民共和国", "synonyms": null }, { "name": "中华", "nature": "nz", "offe": 0, "realName": "中华", "synonyms": null } ] }Response fields:
Field
Description
nameThe token resulting from tokenization.
natureThe part-of-speech tag, such as
nfor noun,vfor verb,nsfor place name, orntfor organization name.offeThe starting offset of the token in the original text.
realNameThe original form of the term.
synonymsA list of synonyms. Returns
nullif no synonym was configured or triggered for this token.
HTTP API reference
API | Method | Description |
| GET | Performs dedicated tokenization tests and diagnostics. Supports various parameters. |
| GET | Displays the effective global configuration and the list of loaded dictionary files in the current cluster's memory. |
| GET | Refreshes the |
| GET | Refreshes and hot-reloads the dictionary tree content on all nodes in the cluster. |
Query parameters for the
GET /_cat/ansjAPI:Parameter
Required
Description
textYes
The source text to be tokenized.
typeYes
The tokenizer type to use for testing:
base_ansj,index_ansj,query_ansj,dic_ansj, ornlp_ansj.dicNo
The key for the custom user dictionary. Separate multiple keys with commas.
stopNo
The key for the stopword dictionary. Separate multiple keys with commas.
ambiguityNo
The key for the ambiguity dictionary.
synonymsNo
The key for the synonym dictionary. Separate multiple keys with commas.
crfNo
Specifies the CRF model key. This is effective only in
nlp_ansjmode.isNameRecognitionNo
Overrides the global setting for name recognition.
isNumRecognitionNo
Overrides the global setting for number recognition.
isQuantifierRecognitionNo
Overrides the global setting for quantifier merging.
isRealNameNo
Overrides the global setting for keeping the original term.
Complete request example:
GET /_cat/ansj?text=中国有56个民族&type=index_ansj&dic=dic&stop=stop&synonyms=synonyms
FAQ
Q1: How to fix unexpected tokenization?
Check the tokenizer type: First, confirm that the tokenizer you are using is appropriate for the scenario. We generally recommend using
index_ansjfor high recall during indexing andquery_ansjfor high precision during search.Perform a quick comparison: Use the dedicated test API
GET /_cat/ansj?text=<your_text>&type=<tokenizer>with different tokenizer types to observe their behavior.Verify dictionary content: Check that your custom user dictionary contains the expected terms. Ensure the dictionary file follows the
term part_of_speech term_frequencyformat and has no formatting errors, garbled characters, or extra spaces.Verify global settings: Check the
ansj.cfg.ymlconfiguration file to ensure that features likeisNameRecognition(name recognition) andisNumRecognition(number recognition) are not accidentally disabled.
Q2: Why are my dictionary updates not working?
Check the upload status in the console: Confirm that the dictionary file has uploaded successfully (the "Upload Dictionary" button has changed from gray back to blue).
Check the YAML mapping: Confirm that your
ansj.cfg.ymlconfiguration file correctly associates the new file with the correct key using parameters likedic_extraordic.Check if the configuration was refreshed: If you modified the
ansj.cfg.ymlfile, you must first call the configuration refresh API:GET /_ansj/flush/config.Confirm if the dictionary was hot-reloaded: Ensure that you have called the dictionary refresh command:
GET /_ansj/flush/dic?key=<your_dictionary_key>.Confirm the system's loaded state: Run the
GET /_cat/ansj/configAPI to check the latest status of the dictionary file in the response and confirm that it has been correctly loaded into memory.
Q3: When to use each tokenizer type?
Scenario | Recommended tokenizer | Reason |
Indexing documents |
| Uses fine-grained tokenization to extract more sub-terms, which improves search recall. |
Executing front-end search queries |
| Uses coarse-grained tokenization to split text into logical phrases. This approach prevents over-splitting, which can create irrelevant noise and reduce search precision. |
Vertical or domain-specific search |
| Forces industry-specific terms in a custom dictionary to remain intact. This is suitable for fields such as medicine, law, or engineering that have many fixed proper nouns. |
In-depth semantic text analysis |
| Based on a Conditional Random Field (CRF) model. Although it consumes more resources, it provides extremely high accuracy for entity recognition and tokenizing unstructured paragraphs. |
Minimal text matching |
| Performs only the most basic atomic splitting without loading any extra logic. Offers the highest performance. |