Use the analysis-ansj plugin

Updated at:

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_ansj

index mode

Adds sub-word splitting to standard tokenization to generate more tokens and improve search recall.

Recommended for indexing.

query_ansj

query mode

Standard tokenization that generates fewer but more meaningful tokens to improve query precision.

Recommended for searching.

dic_ansj

user dictionary mode

Prioritizes matching terms in the user dictionary.

For scenarios requiring forced recognition of specific terms.

base_ansj

base mode

The most basic tokenization method.

Scenarios where tokenization precision is not a high priority.

nlp_ansj

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

dic

Stores custom, business-specific new terms.

Stopword dictionary

stop

Stores meaningless terms, such as the or a, to be filtered out. These terms are not added to the inverted index.

Ambiguity dictionary

ambiguity

Resolves tokenization ambiguity by forcing a specific segmentation for certain text combinations.

Synonym dictionary

synonyms

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.

    Important

    Updating 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.yml in the console.

  • Deletea dictionary: You can delete a dictionary if it is no longer needed.

    Important
    • Deleting 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_query to 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.

  1. Create or modify a YAML configuration file named ansj.cfg.yml on your local machine. Configure global control parameters and dictionary mappings as needed.

  2. 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.dic

    Global parameters

    Parameter

    Type

    Default

    Description

    isNameRecognition

    boolean

    true

    Enables Chinese name recognition.

    isNumRecognition

    boolean

    true

    Enables number recognition.

    isQuantifierRecognition

    boolean

    true

    Specifies whether to merge numbers and quantifiers.

    isRealName

    boolean

    false

    Specifies whether to keep the original term.

    isSkipUserDefine

    boolean

    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

type

string

Tokenizer type. Valid values: index_ansj, query_ansj, dic_ansj, base_ansj, nlp_ansj.

dic

string

User dictionary key. Separate multiple keys with commas.

stop

string

Stopword dictionary key. Separate multiple keys with commas.

ambiguity

string

Ambiguity dictionary key.

synonyms

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

  1. Upload the new dictionary file to the appropriate category.

  2. If you added a new dictionary, modify the ansj.cfg.yml file to add the dictionary key, upload the configuration file, and then call the API to refresh the configuration.

  3. Call the API to refresh the dictionary.

Refresh dictionaries across the cluster

  • Request: GET /_ansj/flush/dic?key=dic

  • Parameters:

    Key

    Description

    dic

    Refreshes the default user dictionary.

    dic_<custom_name>

    Refreshes the user dictionary with the specified name.

    stop

    Refreshes the default stopword dictionary.

    stop_<custom_name>

    Refreshes the stopword dictionary with the specified name.

    ambiguity

    Refreshes the default ambiguity dictionary.

    ambiguity_<custom_name>

    Refreshes the ambiguity dictionary with the specified name.

    synonyms

    Refreshes 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

Warning

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 into machine and learning during 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

  1. Step 1: Create a basic test index. Use index_ansj during indexing for fine-grained tokenization to improve recall, and use query_ansj during 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"
          }
        }
      }
    }
  2. Step 2: Test the validity of the analyzer configuration.

    POST /test_index/_analyze
    {
      "field": "test_field",
      "text": "中国"
    }
  3. 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" : "中国是社会主义国家" }
  4. 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_d1
  • Example response:

    {
      "result": [
        {
          "name": "中华人民共和国",
          "nature": "ns",
          "offe": 0,
          "realName": "中华人民共和国",
          "synonyms": null
        },
        {
          "name": "中华",
          "nature": "nz",
          "offe": 0,
          "realName": "中华",
          "synonyms": null
        }
      ]
    }
    
  • Response fields:

    Field

    Description

    name

    The token resulting from tokenization.

    nature

    The part-of-speech tag, such as n for noun, v for verb, ns for place name, or nt for organization name.

    offe

    The starting offset of the token in the original text.

    realName

    The original form of the term.

    synonyms

    A list of synonyms. Returns null if no synonym was configured or triggered for this token.

HTTP API reference

API

Method

Description

/_cat/ansj

GET

Performs dedicated tokenization tests and diagnostics. Supports various parameters.

/_cat/ansj/config

GET

Displays the effective global configuration and the list of loaded dictionary files in the current cluster's memory.

/_ansj/flush/config

GET

Refreshes the ansj.cfg.yml configuration file on all nodes in the cluster.

/_ansj/flush/dic

GET

Refreshes and hot-reloads the dictionary tree content on all nodes in the cluster.

  • Query parameters for the GET /_cat/ansj API:

    Parameter

    Required

    Description

    text

    Yes

    The source text to be tokenized.

    type

    Yes

    The tokenizer type to use for testing: base_ansj, index_ansj, query_ansj, dic_ansj, or nlp_ansj.

    dic

    No

    The key for the custom user dictionary. Separate multiple keys with commas.

    stop

    No

    The key for the stopword dictionary. Separate multiple keys with commas.

    ambiguity

    No

    The key for the ambiguity dictionary.

    synonyms

    No

    The key for the synonym dictionary. Separate multiple keys with commas.

    crf

    No

    Specifies the CRF model key. This is effective only in nlp_ansj mode.

    isNameRecognition

    No

    Overrides the global setting for name recognition.

    isNumRecognition

    No

    Overrides the global setting for number recognition.

    isQuantifierRecognition

    No

    Overrides the global setting for quantifier merging.

    isRealName

    No

    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?

  1. Check the tokenizer type: First, confirm that the tokenizer you are using is appropriate for the scenario. We generally recommend using index_ansj for high recall during indexing and query_ansj for high precision during search.

  2. 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.

  3. Verify dictionary content: Check that your custom user dictionary contains the expected terms. Ensure the dictionary file follows the term part_of_speech term_frequency format and has no formatting errors, garbled characters, or extra spaces.

  4. Verify global settings: Check the ansj.cfg.yml configuration file to ensure that features like isNameRecognition (name recognition) and isNumRecognition (number recognition) are not accidentally disabled.

Q2: Why are my dictionary updates not working?

  1. 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).

  2. Check the YAML mapping: Confirm that your ansj.cfg.yml configuration file correctly associates the new file with the correct key using parameters like dic_extra or dic.

  3. Check if the configuration was refreshed: If you modified the ansj.cfg.yml file, you must first call the configuration refresh API: GET /_ansj/flush/config.

  4. Confirm if the dictionary was hot-reloaded: Ensure that you have called the dictionary refresh command: GET /_ansj/flush/dic?key=<your_dictionary_key>.

  5. Confirm the system's loaded state: Run the GET /_cat/ansj/config API 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

index_ansj

Uses fine-grained tokenization to extract more sub-terms, which improves search recall.

Executing front-end search queries

query_ansj

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

dic_ansj

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

nlp_ansj

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

base_ansj

Performs only the most basic atomic splitting without loading any extra logic. Offers the highest performance.