2.X/3. Dealing with Human Language

3-4-3. Hunspell Stemmer

drscg 2017. 9. 24. 13:17

Elasticsearch provides dictionary-based stemming via the hunspell token filter. Hunspell hunspell.github.io is the spell checker used by Open Office, LibreOffice, Chrome, Firefox, Thunderbird, and many other open and closed source projects.

Elasticsearch는 hunspell token filter를 통해, 사전 기반의 형태소 분석을 제공한다. Hunspell hunspell.sourceforge.net은 Open Office, Libre Office, Chrome, FireFox, Thunderbird 그리고 많은 Open/Close source project에서 사용되는, 맞춤법 검사 프로그램이다.

Hunspell dictionaries can be obtained from the following:

hunspell 사전은 아래에서 얻을 수 있다.

A Hunspell dictionary consists of two files with the same base name—such as en_US—but with one of two extensions:

hunspell 사전은 en_US 같은, 동일한 기본 이름을 가진 2개의 파일(확장자는 아래 둘 중의 하나)로 구성되어 있다.

.dic

Contains all the root words, in alphabetical order, plus a code representing all possible suffixes and prefixes (which collectively are known as affixes)

원형 모두를 알파벳순으로 포함, 모든 가능한 접두사와 접미사(묶어서 접사(affixes) 라고 함)를 나타내는, code를 추가로 포함.

.aff

Contains the actual prefix or suffix transformation for each code listed in the .dic file

.dic 파일에 나열된 code 각각에 대한, 실제 접두사와 접미사의 변화를 포함

Installing a Dictionaryedit

The Hunspell token filter looks for dictionaries within a dedicated Hunspell directory, which defaults to ./config/hunspell/. The .dic and .aff files should be placed in a subdirectory whose name represents the language or locale of the dictionaries. For instance, we could create a Hunspell stemmer for American English with the following layout:

hunspell token filter는, Hunspell 전용 디렉토리(기본: ./config/hunspell/)에서, 사전을 찾는다. .dic 와.aff 파일은, 사전의 언어나 locale의 이름을 나타내는, 하위 디렉토리에 있어야 한다. 예를 들자면, 미국 영어를 위한 hunspell 형태소 분석기는 아래의 형태로 생성할 수 있다.

config/
   hunspell/ 
       en_US/ 
           en_US.dic
           en_US.aff
           settings.yml 

hunspell 디렉토리의 위치는 설정으로 변경할 수 있다. config/elasticsearch.yml file의 indices.analysis.hunspell.dictionary.location

en_US 는 hunspell token filter에 넘겨 주는 locale이나 언어(language) 의 이름일 것이다.

언어별 설정 파일은 아래를 참고하자.

Per-Language Settingsedit

The settings.yml file contains settings that apply to all of the dictionaries within the language directory, such as these:

setting.yml 은 아래와 같이, 언어(language) 디렉토리 내의 사전 모두에 적용할, 설정을 가지고 있다.

---
ignore_case:          true
strict_affix_parsing: true

The meaning of these settings is as follows:

이 설정의 의미는 아래와 같다.

ignore_case

Hunspell dictionaries are case sensitive by default: the surname Booker is a different word from the noun booker, and so should be stemmed differently. It may seem like a good idea to use the hunspell stemmer in case-sensitive mode, but that can complicate things:

hunspell 사전은 기본적으로 대소문자를 구분한다. 성(姓)을 나타내는 Booker 라는 단어는 명사 booker 와 다른 단어이다. 따라서 다르게 형태소 분석된다. 대소문자를 구분하는 상황에서, hunspell형태소 분석기를 사용하는 것은 좋은 생각이다. 하지만, 복잡해 질 수 있다.

  • A word at the beginning of a sentence will be capitalized, and thus appear to be a proper noun.

    문장의 처음에 오는 단어는 대문자로 시작할 것이다. 따라서, 고유명사로 나타날 것이다.

  • The input text may be all uppercase, in which case almost no words will be found.

    입력 텍스트가 모두 대문자인 경우, 단어가 거의 발견되지 않을 수 있다.

  • The user may search for names in all lowercase, in which case no capitalized words will be found.

    사용자가 이름을 모두 소문자로 검색하는 경우, 대문자로 된 단어는 검색되지 않는다.

As a general rule, it is a good idea to set ignore_case to true.

일반적으로, ignore_case 를 true 로 설정하는 것이 좋다.

strict_affix_parsing

The quality of dictionaries varies greatly. Some dictionaries that are available online have malformed rules in the .aff file. By default, Lucene will throw an exception if it can’t parse an affix rule. If you need to deal with a broken affix file, you can set strict_affix_parsing to falseto tell Lucene to ignore the broken rules.

사전의 질은 매우 다양하다. 온라인에서 이용할 수 있는 몇몇 사전은 .aff 파일에 알맞지 않은 규칙을 가지고 있다. 기본적으로, 접사(접두사, 접미사) 규칙을 분석할 수 없으면, Lucene에서 예외가 발생한다. 알맞지 않은 규칙을 가진 접사 파일을 다루는 경우, strict_affix_parsing 을 false 로 설정하여, Lucene이 알맞지 않은 규칙을 무시하도록 할 수 있다.

Creating a Hunspell Token Filteredit

Once your dictionaries are installed on all nodes, you can define a hunspell token filter that uses them:

사전이 모든 node에 설치가 되면, 그것을 사용할 hunspell token filter를 정의할 수 있다.

PUT /my_index
{
  "settings": {
    "analysis": {
      "filter": {
        "en_US": {
          "type":     "hunspell",
          "language": "en_US" 
        }
      },
      "analyzer": {
        "en_US": {
          "tokenizer":  "standard",
          "filter":   [ "lowercase", "en_US" ]
        }
      }
    }
  }
}

language 는 사전이 있는 디렉토리와 동일한 이름을 가진다.

You can test the new analyzer with the analyze API, and compare its output to that of the englishanalyzer:

analyze API를 이용해, 새로운 analyzer를 테스트해 보고, 출력을 english analyzer와 비교해 보자.

GET /my_index/_analyze?analyzer=en_US 
reorganizes

GET /_analyze?analyzer=english 
reorganizes

organize 를 반환

reorgan 을 반환

An interesting property of the hunspell stemmer, as can be seen in the preceding example, is that it can remove prefixes as well as as suffixes. Most algorithmic stemmers remove suffixes only.

위의 예제에서 알 수 있듯이, hunspell 형태소 분석기의 흥미로운 특성은 접미사뿐만 아니라 접두사를 제거할 수 있다는 것이다. 대부분의 형태소 분석기는 접미사만을 제거한다.

Tip

Hunspell dictionaries can consume a few megabytes of RAM. Fortunately, Elasticsearch creates only a single instance of a dictionary per node. All shards that use the same Hunspell analyzer share the same instance.

Hunspell 사전은 수 MB의 RAM을 사용할 수 있다. 다행히도, Elasticsearch는 node당 하나의 사전 인스턴스만을 생성한다. 동일한 hunspell analyzer를 사용하는 모든 shard는 동일한 인스턴스를 공유한다.

Hunspell Dictionary Formatedit

While it is not necessary to understand the format of a Hunspell dictionary in order to use the hunspell tokenizer, understanding the format will help you write your own custom dictionaries. It is quite simple.

hunspell tokenizer를 사용하기 위해, hunspell 사전의 형식을 이해할 필요는 없지만, 형식을 이해하면, 자기 자신만의 사용자 정의 사전을 만드는데 도움이 된다. 매우 간단하다.

For instance, in the US English dictionary, the en_US.dic file contains an entry for the word analyze, which looks like this:

예를 들어, US 영어 사전에서, en_US.dic 파일은 아래처럼 보이는 단어 analyze 항목을 포함하고 있다.

analyze/ADSG

The en_US.aff file contains the prefix or suffix rules for the AGD, and S flags. Each flag consists of a number of rules, only one of which should match. Each rule has the following format:

en_US.aff 파일은 AGDS 플래그에 대한 접두사 또는 접미사 규칙을 포함하고 있다. 각 플래그는 많은 규칙으로 구성되어 있고, 일치하는 것은 단 하나이다. 각 규칙의 형식은 아래와 같다.

[type] [flag] [letters to remove] [letters to add] [condition]

For instance, the following is suffix (SFX) rule D. It says that, when a word ends in a consonant (anything but aeio, or u) followed by a y, it can have the y removed and ied added (for example, ready → readied).

예를 들면, 아래의 접미사(SFX) 규칙 D 를 보면, 단어가 자음(aeiou 제외) 다음에 y 로 끝나면, y를 제거하고, ied 를 추가한다. (예: ready → readied)

SFX    D      y   ied  [^aeiou]y

The rules for the AGD, and S flags mentioned previously are as follows:

위에서 언급된 AGDS 플래그에 대한 규칙은 아래와 같다.

SFX D Y 4
SFX D   0     d          e 
SFX D   y     ied        [^aeiou]y
SFX D   0     ed         [^ey]
SFX D   0     ed         [aeiou]y

SFX S Y 4
SFX S   y     ies        [^aeiou]y
SFX S   0     s          [aeiou]y
SFX S   0     es         [sxzh]
SFX S   0     s          [^sxzhy] 

SFX G Y 2
SFX G   e     ing        e 
SFX G   0     ing        [^e]

PFX A Y 1
PFX A   0     re         . 

analyze 는 e 로 끝난다. 따라서, d 를 추가하여, analyzed 가 된다.

analyze 는 sxzhy 로 끝나지 않는다. 따라서, s 를 추가하여, analyzes 가 된다.

analyze 는 e 로 끝난다. 따라서, e 를 제거하고 ing 를 추가하여, analyzing 이 된다.

접두사 re 가 추가되어, reanalyze 가 된다. 이 규칙은 접미사 규칙과 조합되어, reanalyzesreanalyzedreanalyzing 이 된다.

More information about the Hunspell syntax can be found on the Hunspell documentation site.

hunspell 문법에 대한 더 많은 정보는 Hunspell documentation에서 볼 수 있다.


'2.X > 3. Dealing with Human Language' 카테고리의 다른 글

3-4-1. Algorithmic Stemmers  (0) 2017.09.24
3-4-2. Dictionary Stemmers  (0) 2017.09.24
3-4-4. Choosing a Stemmer  (0) 2017.09.24
3-4-5. Controlling Stemming  (0) 2017.09.24
3-4-6. Stemming in situ  (0) 2017.09.24