'analyzer'에 해당되는 글 10건

  1. 2017.02.21 [Elasticsearch] elasticsearch-analysis-arirang-5.2.1
  2. 2016.04.22 [Elasticsearch] Analyzer filter 구성 시 순서.
  3. 2016.03.16 [Elasticsearch] Arirang analyzer 버전 올렸습니다.
  4. 2015.11.20 [Elasticsearch] 한글 자모 형태소 분석기 플러그인.
  5. 2015.11.04 [Elasticsearch] lucene arirang analyzer 플러그인 적용 on elasticsearch 2.0
  6. 2014.11.11 [Analyzer] 형태소 분석기.
  7. 2014.11.05 [Lucene] 4.9.0 analyzer & tokenizer....
  8. 2014.04.30 [Elasticsearch] lucene arirang analyzer plugin.
  9. 2014.04.30 [lucene] arirang maven build 하기.
  10. 2013.08.21 [Lucene] Analysis JavaDoc

[Elasticsearch] elasticsearch-analysis-arirang-5.2.1

Elastic/Elasticsearch 2017.02.21 12:41

elasticsearch-analysis-arirang-5.2.1 공유 합니다.


Lucene 6.4.1

Elasticsearch 5.2.1 

기준 입니다.


elasticsearch-analysis-arirang-5.2.1.zip


설치 방법)

$ bin/elasticsearch-plugin install --verbose file:///services/apps/elasticsearch-analysis-arirang-5.2.1.zip


저작자 표시 비영리 변경 금지
신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Elasticsearch] Analyzer filter 구성 시 순서.

Elastic/Elasticsearch 2016.04.22 11:42

아주 기본적인 내용인데 간혹 놓치고 가는 경우가 있어서 기록해 봅니다.

저 같은 경우는 synonyms 적용하면서 당연히 적용된 줄 알고 테스트 하다 삽질한 경우 입니다.


analyzer 구성은 잘 아시겠지만 settings 에서 수행하게 됩니다.

그리고 설정한 analyzer 를 mappings 에서 사용을 하게 되구요.


설정 방법에 대해서는 아래 문서 참고 하시기 바랍니다.


참고문서)

https://www.elastic.co/guide/en/elasticsearch/reference/2.3/analysis.html


참고문서 내 설정 예시)

index : analysis : analyzer : standard : type : standard stopwords : [stop1, stop2] myAnalyzer1 : type : standard stopwords : [stop1, stop2, stop3] max_token_length : 500 # configure a custom analyzer which is # exactly like the default standard analyzer myAnalyzer2 : tokenizer : standard filter : [standard, lowercase, stop] tokenizer : myTokenizer1 : type : standard max_token_length : 900 myTokenizer2 : type : keyword buffer_size : 512 filter : myTokenFilter1 : type : stop stopwords : [stop1, stop2, stop3, stop4] myTokenFilter2 : type : length min : 0 max : 2000



위 예시를 가지고 설명을 드리면, myAnalyzer2 설정에 filter : [standard, lowercase, stop] 으로 정의가 되어 있습니다.

즉, filter 적용 순서가

1. standard

2. lowercase

3. stop

으로 적용이 된다고 보시면 됩니다.


아주 간단하죠.

제가 설정 순서를 잘못해 놓고 왜 안되지 하고 있었습니다. ㅡ.ㅡ;

저작자 표시 비영리 변경 금지
신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Elasticsearch] Arirang analyzer 버전 올렸습니다.

Elastic/Elasticsearch 2016.03.16 16:38

작업 하는 김에 버전 올렸습니다.


git branch)


루씬 한글 형태소 분석기인 arirang analyzer 버전 올렸습니다.
Elasticsearch 2.2.0
Lucene 5.4.1
arirang.morph 1.0.3

빌드 및 설치 방법)
$ mvn clean package
$ bin/plugin install file:/git/elasticsearch-analysis-arirang/target/elasticsearch-analysis-arirang.zip

인덱스 세팅 방법)
"index": {
"analysis": {
"analyzer": {
"arirang_custom": {
"type": "arirang_analyzer",
"tokenizer": "arirang_tokenizer",
"filter": ["lowercase", "trim", "arirang_filter"]
}
}
}

analyze 테스트 방법)
$ curl -XGET http://localhost:9200/memebox_deal_idx/_analyze?pretty -d '{ "analyzer":"arirang_analyzer", "text":"elasticsearch 한국 사용자 그룹입니다." }' { "tokens" : [ { "token" : "elasticsearch", "start_offset" : 0, "end_offset" : 13, "type" : "word", "position" : 0 }, { "token" : "한국", "start_offset" : 14, "end_offset" : 16, "type" : "korean", "position" : 1 }, { "token" : "사용자", "start_offset" : 17, "end_offset" : 20, "type" : "korean", "position" : 2 }, { "token" : "그룹", "start_offset" : 21, "end_offset" : 23, "type" : "korean", "position" : 3 } ] }


사전 reload 방법)

$ curl -XGET http://localhost:9200/_arirang_dictionary_reload

- 클러스터 재시작 없이 사전 데이터 수정 후 리로드 잘 됩니다. 단, 이미 색인 된 문서들은 재색인 해야 합니다.

저작자 표시 비영리 변경 금지
신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Elasticsearch] 한글 자모 형태소 분석기 플러그인.

Elastic/Elasticsearch 2015.11.20 00:07

짜집기 코드를 활용해서 플러그인을 만들어 봤습니다.

소스 코드는 아래에서 받아 보실 수 있습니다.


[repository]

https://github.com/HowookJeong/elasticsearch-analysis-hangueljamo


[빌드방법]

$ mvn clean package


  • Elasticsearch Analyze Test URL
http://localhost:9200/test/_analyze?analyzer=hangueljamo_analyzer&text=Henry 노트북&pretty=1
  • Analyzed Result
{
  "tokens" : [ {
    "token" : "henry",
    "start_offset" : 0,
    "end_offset" : 5,
    "type" : "word",
    "position" : 0
  }, {
    "token" : "ㄴㅌㅂ",
    "start_offset" : 6,
    "end_offset" : 9,
    "type" : "word",
    "position" : 1
  } ]
}


저작자 표시 비영리 변경 금지
신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Elasticsearch] lucene arirang analyzer 플러그인 적용 on elasticsearch 2.0

Elastic/Elasticsearch 2015.11.04 15:37

elasticsearch 2.0 GA 기념으로 수명님의 lucene arirang 한글분석기 적용방법을 알아 보도록 하겠습니다.

이전에 작성된 elasticsearch analyzer arirang 은 아래 글 참고 부탁 드립니다.


http://jjeong.tistory.com/958


[Requirement]

elasticsearch 2.0

jdk 1.7 이상 (elastic 에서 추천 하는 버전은 1.8 이상입니다.)

maven 3.1 이상

arirang.lucene-analyzer-5.0-1.0.0.jar (http://cafe.naver.com/korlucene/1274)

arirang-morph-1.0.0.jar (http://cafe.naver.com/korlucene/1274)


[Analysis Plugins]

https://www.elastic.co/guide/en/elasticsearch/plugins/2.0/analysis.html


[Plugin 작성 시 변경 내용 - 하나]

- es-plugin.properties 파일이 없어 지고 plugin-descriptor.properties 가 생겼습니다.

- plugin-descriptor.properties 내용은 아래와 같습니다.


classname=org.elasticsearch.plugin.analysis.arirang.AnalysisArirangPlugin

name=arirang

jvm=true

java.version=1.7

site=false

isolated=true

description=Arirang plugin

version=${project.version}

elasticsearch.version=${elasticsearch.version}

hash=${buildNumber}

timestamp=${timestamp}


▶ 자세한 설명을 원하시는 분들은 아래 링크 참고 하시면 됩니다.

https://www.elastic.co/guide/en/elasticsearch/plugins/current/plugin-authors.html#_plugin_descriptor_file


[Plugin 작성 시 변경 내용 - 둘]

- 기존에 상속 받았던 AbstractPlugin이 없어지고 Plugin을 상속 받아 구현하도록 변경 되었습니다.

From.

public class AnalysisArirangPlugin extends AbstractPlugin {...}


To.

public class AnalysisArirangPlugin extends Plugin {...}


그 밖에는 변경된 내용은 아래 arirang 에서 바뀐 부분이 적용된 내용이 전부 입니다.


[Arirang 변경 내용]

- KoreanAnalyzer 에서 lucene version 정보를 받았으나 이제는 정보를 받지 않습니다.

From.

analyzer = new KoreanAnalyzer(Lucene.VERSION.LUCENE_47);


To.

analyzer = new KoreanAnalyzer();


- KoreanTokenizer 에서는 기존에 reader 정보를 받았으나 이제는 정보를 받지 않습니다.

From.

return new KoreanTokenizer(reader);


To.

return new KoreanTokenizer();


[2.0 적용 시 바뀐 내용]

- assemblies/plugin.xml을 수정 하였습니다.

plugins 폴더에 zip 파일 올려 두고 압축 풀면 바로 동작 할 수 있도록 구성을 변경 하였습니다.


<?xml version="1.0"?>

<assembly>

  <id>plugin</id>

  <formats>

      <format>zip</format>

  </formats>

  <includeBaseDirectory>false</includeBaseDirectory>


  <files>

    <file>

      <source>lib/arirang.lucene-analyzer-5.0-1.0.0.jar</source>

      <outputDirectory>analysis-arirang</outputDirectory>

    </file>

    <file>

      <source>lib/arirang-morph-1.0.0.jar</source>

      <outputDirectory>analysis-arirang</outputDirectory>

    </file>

    <file>

      <source>target/elasticsearch-analysis-arirang-1.0.0.jar</source>

      <outputDirectory>analysis-arirang</outputDirectory>

    </file>

    <file>

      <source>${basedir}/src/main/resources/plugin-descriptor.properties</source>

      <outputDirectory>analysis-arirang</outputDirectory>

      <filtered>true</filtered>

    </file>

  </files>

</assembly>

코드는 직관적이라서 쉽게 이해 하실 수 있을 거라 생각 합니다.

필요한 jar 파일들과 properties 파일을 analysis-arirang 이라는 폴더로 묶는 것입니다.

<filtered>true</filtered> 옵션은 아래 링크 참고 하세요. (해당 파일이 filtering 되었는지 확인 하는 것입니다.)

https://maven.apache.org/plugins/maven-assembly-plugin/assembly.html#class_file


여기서 plugin-descriptor.properties 파일이 포함이 안되어 있게 되면 elasticsearch 실행 시 에러가 발생하고 실행이 안됩니다.

주의 하셔야 하는 부분(?) 입니다.


- plugin-descriptor.properties 파일 없을 때 에러 메시지


[2015-11-04 12:34:14,522][INFO ][node                     ] [Lady Jacqueline Falsworth Crichton] initializing ...


Exception in thread "main" java.lang.IllegalStateException: Unable to initialize plugins

Likely root cause: java.nio.file.NoSuchFileException: /Users/hwjeong/server/app/elasticsearch/elasticsearch-2.0.0/plugins/analysis-arirang/plugin-descriptor.properties

at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)

at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)

at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)

at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)

at java.nio.file.Files.newByteChannel(Files.java:315)

at java.nio.file.Files.newByteChannel(Files.java:361)

at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:380)

at java.nio.file.Files.newInputStream(Files.java:106)

at org.elasticsearch.plugins.PluginInfo.readFromProperties(PluginInfo.java:86)

at org.elasticsearch.plugins.PluginsService.getPluginBundles(PluginsService.java:306)

at org.elasticsearch.plugins.PluginsService.<init>(PluginsService.java:112)

at org.elasticsearch.node.Node.<init>(Node.java:144)

at org.elasticsearch.node.NodeBuilder.build(NodeBuilder.java:145)

at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:170)

at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:270)

at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:35)

Refer to the log for complete error details.


- Test Code 추가

뭐가 coverage 를 올리기 위한 그런 테스트 코드는 아닙니다. ;;


▶ ArirangAnalysisTest.java


이 테스트는 elasticsearch에서 실제 작성된 플러그인이 제대로 module 로 등록 되고 등록된 module에 대한 service 를 가져 오는지 보는 것입니다.

elasticsearch 소스코드를 내려 받으시면 plugins 에 들어 있는 코드 그대로 copy & paste 한 것입니다.


▶ ArirangAnalyzerTest.java


이 테스트는 _analyze 에 대한 REST API 와 실제 index.analysis 세팅 사이에 구성이 어떻게 코드로 반영 되는지 상호 맵핑 하기 위해 작성 되었습니다.

analyzer, tokenizer, tokenfilter 에 대해서 어떻게 동작 하는지 그나마 쉽게 이해 하시는데 도움이 될까 싶어 작성된 코드 입니다.


※ Elasticsearch Test Suite 이슈 - 자답(?)

현재 master branch 는 문제 없이 잘 됩니다.

다만 2.0 branch 에서는 아래와 같은 또는 다른 문제가 발생을 합니다.

그냥 master 받아서 테스트 하시길 권장 합니다.


※ Elasticsearch Test Suite 이슈.

이건 제가 잘못해서 발생 한 것일 수도 있기 때문에 혹시 해결 하신 분이 계시면 공유 좀 부탁 드립니다.


▶ 발생 에러

/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/bin/java -ea -Didea.launcher.port=7533 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 14 CE.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA 14 CE.app/Contents/lib/idea_rt.jar:/Applications/IntelliJ IDEA 14 CE.app/Contents/plugins/junit/lib/junit-rt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/lib/javafx-doclet.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/lib/tools.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/htmlconverter.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_55.jdk/Contents/Home/jre/lib/rt.jar:/Users/hwjeong/git/elasticsearch-analysis-arirang/target/test-classes:/Users/hwjeong/git/elasticsearch-analysis-arirang/target/classes:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-core/5.2.1/lucene-core-5.2.1.jar:/Users/hwjeong/.m2/repository/org/elasticsearch/elasticsearch/2.0.0/elasticsearch-2.0.0.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-backward-codecs/5.2.1/lucene-backward-codecs-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-analyzers-common/5.2.1/lucene-analyzers-common-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-queries/5.2.1/lucene-queries-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-memory/5.2.1/lucene-memory-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-highlighter/5.2.1/lucene-highlighter-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-queryparser/5.2.1/lucene-queryparser-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-sandbox/5.2.1/lucene-sandbox-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-suggest/5.2.1/lucene-suggest-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-misc/5.2.1/lucene-misc-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-join/5.2.1/lucene-join-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-grouping/5.2.1/lucene-grouping-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-spatial/5.2.1/lucene-spatial-5.2.1.jar:/Users/hwjeong/.m2/repository/com/spatial4j/spatial4j/0.4.1/spatial4j-0.4.1.jar:/Users/hwjeong/.m2/repository/com/google/guava/guava/18.0/guava-18.0.jar:/Users/hwjeong/.m2/repository/com/carrotsearch/hppc/0.7.1/hppc-0.7.1.jar:/Users/hwjeong/.m2/repository/joda-time/joda-time/2.8.2/joda-time-2.8.2.jar:/Users/hwjeong/.m2/repository/org/joda/joda-convert/1.2/joda-convert-1.2.jar:/Users/hwjeong/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.5.3/jackson-core-2.5.3.jar:/Users/hwjeong/.m2/repository/com/fasterxml/jackson/dataformat/jackson-dataformat-smile/2.5.3/jackson-dataformat-smile-2.5.3.jar:/Users/hwjeong/.m2/repository/com/fasterxml/jackson/dataformat/jackson-dataformat-yaml/2.5.3/jackson-dataformat-yaml-2.5.3.jar:/Users/hwjeong/.m2/repository/org/yaml/snakeyaml/1.12/snakeyaml-1.12.jar:/Users/hwjeong/.m2/repository/com/fasterxml/jackson/dataformat/jackson-dataformat-cbor/2.5.3/jackson-dataformat-cbor-2.5.3.jar:/Users/hwjeong/.m2/repository/io/netty/netty/3.10.5.Final/netty-3.10.5.Final.jar:/Users/hwjeong/.m2/repository/com/ning/compress-lzf/1.0.2/compress-lzf-1.0.2.jar:/Users/hwjeong/.m2/repository/com/tdunning/t-digest/3.0/t-digest-3.0.jar:/Users/hwjeong/.m2/repository/org/hdrhistogram/HdrHistogram/2.1.6/HdrHistogram-2.1.6.jar:/Users/hwjeong/.m2/repository/commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.jar:/Users/hwjeong/.m2/repository/com/twitter/jsr166e/1.1.0/jsr166e-1.1.0.jar:/Users/hwjeong/.m2/repository/log4j/log4j/1.2.16/log4j-1.2.16.jar:/Users/hwjeong/.m2/repository/org/slf4j/slf4j-api/1.6.2/slf4j-api-1.6.2.jar:/Users/hwjeong/.m2/repository/org/slf4j/slf4j-log4j12/1.6.2/slf4j-log4j12-1.6.2.jar:/Users/hwjeong/git/elasticsearch-analysis-arirang/lib/arirang-morph-1.0.0.jar:/Users/hwjeong/git/elasticsearch-analysis-arirang/lib/arirang.lucene-analyzer-5.0-1.0.0.jar:/Users/hwjeong/.m2/repository/junit/junit/4.11/junit-4.11.jar:/Users/hwjeong/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar:/Users/hwjeong/.m2/repository/com/carrotsearch/randomizedtesting/randomizedtesting-runner/2.1.16/randomizedtesting-runner-2.1.16.jar:/Users/hwjeong/.m2/repository/org/hamcrest/hamcrest-all/1.3/hamcrest-all-1.3.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-test-framework/5.2.1/lucene-test-framework-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/lucene/lucene-codecs/5.2.1/lucene-codecs-5.2.1.jar:/Users/hwjeong/.m2/repository/org/apache/ant/ant/1.8.2/ant-1.8.2.jar:/Users/hwjeong/.m2/repository/org/elasticsearch/elasticsearch/2.0.0/elasticsearch-2.0.0-tests.jar:/Users/hwjeong/.m2/repository/net/java/dev/jna/jna/4.1.0/jna-4.1.0.jar" com.intellij.rt.execution.application.AppMain com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 org.elasticsearch.index.analysis.ArirangAnalysisTest,testArirangAnalysis

log4j:WARN No appenders could be found for logger (org.elasticsearch.bootstrap).

log4j:WARN Please initialize the log4j system properly.

log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.


java.lang.RuntimeException: found jar hell in test classpath

at org.elasticsearch.bootstrap.BootstrapForTesting.<clinit>(BootstrapForTesting.java:63)

at org.elasticsearch.test.ESTestCase.<clinit>(ESTestCase.java:106)

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName(Class.java:270)

at com.carrotsearch.randomizedtesting.RandomizedRunner$1.run(RandomizedRunner.java:573)

Caused by: java.lang.IllegalStateException: jar hell!

class: org.hamcrest.BaseDescription

jar1: /Users/hwjeong/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar

jar2: /Users/hwjeong/.m2/repository/org/hamcrest/hamcrest-all/1.3/hamcrest-all-1.3.jar

at org.elasticsearch.bootstrap.JarHell.checkClass(JarHell.java:267)

at org.elasticsearch.bootstrap.JarHell.checkJarHell(JarHell.java:185)

at org.elasticsearch.bootstrap.JarHell.checkJarHell(JarHell.java:86)

at org.elasticsearch.bootstrap.BootstrapForTesting.<clinit>(BootstrapForTesting.java:61)

... 4 more


저작자 표시 비영리 변경 금지
신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Analyzer] 형태소 분석기.

Elastic/Elasticsearch 2014.11.11 16:43

[형태소 분석기]

1) 루씬 기본 standard/cjk (source code 제공)

https://lucene.apache.org/core/4_10_0/analyzers-common/org/apache/lucene/analysis/standard/StandardAnalyzer.html


2) 루씬 arirang (source code 제공)

https://lucenekorean.svn.sourceforge.net/svnroot/lucenekorean/


3)  mecab (jar 제공)

https://bitbucket.org/eunjeon/mecab-ko


4) twitter korean text (source code 제공)

https://github.com/twitter/twitter-korean-text


5) komoran (jar 제공)

http://shineware.tistory.com/entry/KOMORAN-ver-23

저작자 표시 비영리 변경 금지
신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Lucene] 4.9.0 analyzer & tokenizer....

Elastic/Elasticsearch 2014.11.05 13:05

http://lucene.apache.org/core/4_9_0/core/org/apache/lucene/analysis/package-summary.html

https://lucene.apache.org/core/4_9_0/core/org/apache/lucene/analysis/TokenStream.html

Version matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY Analyzer analyzer = new StandardAnalyzer(matchVersion); // or any other analyzer TokenStream ts = analyzer.tokenStream("myfield", new StringReader("some text goes here")); OffsetAttribute offsetAtt = ts.addAttribute(OffsetAttribute.class); try { ts.reset(); // Resets this stream to the beginning. (Required) while (ts.incrementToken()) { // Use AttributeSource.reflectAsString(boolean) // for token stream debugging. System.out.println("token: " + ts.reflectAsString(true)); System.out.println("token start offset: " + offsetAtt.startOffset()); System.out.println(" token end offset: " + offsetAtt.endOffset()); } ts.end(); // Perform end-of-stream operations, e.g. set the final offset. } finally { ts.close(); // Release resources associated with this stream. }


The workflow of the new TokenStream API is as follows:

  1. Instantiation of TokenStream/TokenFilters which add/get attributes to/from the AttributeSource.
  2. The consumer calls reset().
  3. The consumer retrieves attributes from the stream and stores local references to all attributes it wants to access.
  4. The consumer calls incrementToken() until it returns false consuming the attributes after each call.
  5. The consumer calls end() so that any end-of-stream operations can be performed.
  6. The consumer calls close() to release any resource when finished using the TokenStream.



이전 버전이랑 바뀐 내용이 있으니 확인하셔야 합니다. :)

저작자 표시 비영리 변경 금지
신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Elasticsearch] lucene arirang analyzer plugin.

Elastic/Elasticsearch 2014.04.30 18:37

http://jjeong.tistory.com/957

글에 이은 루씬 한국어 형태소 분석기 플러그인 입니다.

일단 잘되내요.. ^^;


형태소 분석기 플러그인 만드는 방법은 아래 글 참고하세요.

http://jjeong.tistory.com/818


https://github.com/HowookJeong/elasticsearch-analysis-arirang

신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[lucene] arirang maven build 하기.

Elastic/Elasticsearch 2014.04.30 15:26

elasticsearch 에 한글형태소 분석기로 arirang 을 적용해 보려고 합니다.

그 전에 먼저 arirang 을 받아서 빌드 테스트를 해보고 lucene 4.7.2 로 빌드가 잘 되면 elasticsearch 1.1.1 용 플러그인으로 만들것입니다.


자세한 내용은 카페에서 확인하세요.

http://cafe.naver.com/korlucene


- SVN

https://lucenekorean.svn.sourceforge.net/svnroot/lucenekorean


- Build 조건

Maven 3.x

JDK 1.7


저는 그냥 

https://lucenekorean.svn.sourceforge.net/svnroot/lucenekorean/arirang.lucene-analyzer-4.6

받아서 4.7.2 로 수정해서 빌드 했습니다.


@수명님이 주의 사항을 카페에 올려 두신게 있는데요 arirang.morph 먼저 빌드 하신 후 analyzer 를 빌드 하셔야 합니다.

이건 pom.xml 열어 보시면 아실듯.. 


일단 4.7.2 로 빌드 잘 되내요.

플러그인 적용 방법은 따로 공유 드리겠습니다.

다 아시는 분들에게는 별로 도움도 안되겠내요.. ^^;;

신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

[Lucene] Analysis JavaDoc

Elastic/Elasticsearch 2013.08.21 10:34

루씬 패키지에 보면 설명이 잘 나와 있습니다.

별도의 analyzer, tokenizer, filter 를 만드셔야 하는 분들은 참고 하시면 좋을 것 같내요.

아래에서 제가 기본적으로 살펴본 부분은 

- Invoking the analyzer

- TokenStream API

이 두 부분 입니다.

이 정도만 보셔도 아마 쉽게 이해 하실 수 있을 거라고 생각 되내요.


[원문]

http://lucene.apache.org/core/4_4_0/core/org/apache/lucene/analysis/package-summary.html


Package org.apache.lucene.analysis Description

API and code to convert text into indexable/searchable tokens. Covers Analyzer and related classes.

Parsing? Tokenization? Analysis!

Lucene, an indexing and search library, accepts only plain text input.

Parsing

Applications that build their search capabilities upon Lucene may support documents in various formats – HTML, XML, PDF, Word – just to name a few. Lucene does not care about the Parsing of these and other document formats, and it is the responsibility of the application using Lucene to use an appropriate Parser to convert the original format into plain text before passing that plain text to Lucene.

Tokenization

Plain text passed to Lucene for indexing goes through a process generally called tokenization. Tokenization is the process of breaking input text into small indexing elements – tokens. The way input text is broken into tokens heavily influences how people will then be able to search for that text. For instance, sentences beginnings and endings can be identified to provide for more accurate phrase and proximity searches (though sentence identification is not provided by Lucene).

In some cases simply breaking the input text into tokens is not enough – a deeper Analysis may be needed. Lucene includes both pre- and post-tokenization analysis facilities.

Pre-tokenization analysis can include (but is not limited to) stripping HTML markup, and transforming or removing text matching arbitrary patterns or sets of fixed strings.

There are many post-tokenization steps that can be done, including (but not limited to):

  • Stemming – Replacing words with their stems. For instance with English stemming "bikes" is replaced with "bike"; now query "bike" can find both documents containing "bike" and those containing "bikes".
  • Stop Words Filtering – Common words like "the", "and" and "a" rarely add any value to a search. Removing them shrinks the index size and increases performance. It may also reduce some "noise" and actually improve search quality.
  • Text Normalization – Stripping accents and other character markings can make for better searching.
  • Synonym Expansion – Adding in synonyms at the same token position as the current word can mean better matching when users search with words in the synonym set.

Core Analysis

The analysis package provides the mechanism to convert Strings and Readers into tokens that can be indexed by Lucene. There are four main classes in the package from which all analysis processes are derived. These are:

  • Analyzer – An Analyzer is responsible for building a TokenStream which can be consumed by the indexing and searching processes. See below for more information on implementing your own Analyzer.
  • CharFilter – CharFilter extends Reader to perform pre-tokenization substitutions, deletions, and/or insertions on an input Reader's text, while providing corrected character offsets to account for these modifications. This capability allows highlighting to function over the original text when indexed tokens are created from CharFilter-modified text with offsets that are not the same as those in the original text. Tokenizers' constructors and reset() methods accept a CharFilter. CharFilters may be chained to perform multiple pre-tokenization modifications.
  • Tokenizer – A Tokenizer is a TokenStream and is responsible for breaking up incoming text into tokens. In most cases, an Analyzer will use a Tokenizer as the first step in the analysis process. However, to modify text prior to tokenization, use a CharStream subclass (see above).
  • TokenFilter – A TokenFilter is also a TokenStream and is responsible for modifying tokens that have been created by the Tokenizer. Common modifications performed by a TokenFilter are: deletion, stemming, synonym injection, and down casing. Not all Analyzers require TokenFilters.

Hints, Tips and Traps

The synergy between Analyzer and Tokenizer is sometimes confusing. To ease this confusion, some clarifications:

Lucene Java provides a number of analysis capabilities, the most commonly used one being the StandardAnalyzer. Many applications will have a long and industrious life with nothing more than the StandardAnalyzer. However, there are a few other classes/packages that are worth mentioning:

  1. PerFieldAnalyzerWrapper – Most Analyzers perform the same operation on all Fields. The PerFieldAnalyzerWrapper can be used to associate a different Analyzer with different Fields.
  2. The analysis library located at the root of the Lucene distribution has a number of different Analyzer implementations to solve a variety of different problems related to searching. Many of the Analyzers are designed to analyze non-English languages.
  3. There are a variety of Tokenizer and TokenFilter implementations in this package. Take a look around, chances are someone has implemented what you need.

Analysis is one of the main causes of performance degradation during indexing. Simply put, the more you analyze the slower the indexing (in most cases). Perhaps your application would be just fine using the simple WhitespaceTokenizer combined with a StopFilter. The benchmark/ library can be useful for testing out the speed of the analysis process.

Invoking the Analyzer

Applications usually do not invoke analysis – Lucene does it for them:

  • At indexing, as a consequence of addDocument(doc), the Analyzer in effect for indexing is invoked for each indexed field of the added document.
  • At search, a QueryParser may invoke the Analyzer during parsing. Note that for some queries, analysis does not take place, e.g. wildcard queries.

However an application might invoke Analysis of any text for testing or for any other purpose, something like:

    Version matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY
    Analyzer analyzer = new StandardAnalyzer(matchVersion); // or any other analyzer
    TokenStream ts = analyzer.tokenStream("myfield", new StringReader("some text goes here"));
    OffsetAttribute offsetAtt = ts.addAttribute(OffsetAttribute.class);
    
    try {
      ts.reset(); // Resets this stream to the beginning. (Required)
      while (ts.incrementToken()) {
        // Use AttributeSource.reflectAsString(boolean)
        // for token stream debugging.
        System.out.println("token: " + ts.reflectAsString(true));

        System.out.println("token start offset: " + offsetAtt.startOffset());
        System.out.println("  token end offset: " + offsetAtt.endOffset());
      }
      ts.end();   // Perform end-of-stream operations, e.g. set the final offset.
    } finally {
      ts.close(); // Release resources associated with this stream.
    }

Indexing Analysis vs. Search Analysis

Selecting the "correct" analyzer is crucial for search quality, and can also affect indexing and search performance. The "correct" analyzer differs between applications. Lucene java's wiki page AnalysisParalysis provides some data on "analyzing your analyzer". Here are some rules of thumb:

  1. Test test test... (did we say test?)
  2. Beware of over analysis – might hurt indexing performance.
  3. Start with same analyzer for indexing and search, otherwise searches would not find what they are supposed to...
  4. In some cases a different analyzer is required for indexing and search, for instance:
    • Certain searches require more stop words to be filtered. (I.e. more than those that were filtered at indexing.)
    • Query expansion by synonyms, acronyms, auto spell correction, etc.
    This might sometimes require a modified analyzer – see the next section on how to do that.

Implementing your own Analyzer

Creating your own Analyzer is straightforward. Your Analyzer can wrap existing analysis components — CharFilter(s) (optional), a Tokenizer, and TokenFilter(s) (optional) — or components you create, or a combination of existing and newly created components. Before pursuing this approach, you may find it worthwhile to explore the analyzers-common library and/or ask on the java-user@lucene.apache.org mailing list first to see if what you need already exists. If you are still committed to creating your own Analyzer, have a look at the source code of any one of the many samples located in this package.

The following sections discuss some aspects of implementing your own analyzer.

Field Section Boundaries

When document.add(field) is called multiple times for the same field name, we could say that each such call creates a new section for that field in that document. In fact, a separate call to tokenStream(field,reader) would take place for each of these so called "sections". However, the default Analyzer behavior is to treat all these sections as one large section. This allows phrase search and proximity search to seamlessly cross boundaries between these "sections". In other words, if a certain field "f" is added like this:

    document.add(new Field("f","first ends",...);
    document.add(new Field("f","starts two",...);
    indexWriter.addDocument(document);

Then, a phrase search for "ends starts" would find that document. Where desired, this behavior can be modified by introducing a "position gap" between consecutive field "sections", simply by overriding Analyzer.getPositionIncrementGap(fieldName):

  Version matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY
  Analyzer myAnalyzer = new StandardAnalyzer(matchVersion) {
    public int getPositionIncrementGap(String fieldName) {
      return 10;
    }
  };

Token Position Increments

By default, all tokens created by Analyzers and Tokenizers have a position increment of one. This means that the position stored for that token in the index would be one more than that of the previous token. Recall that phrase and proximity searches rely on position info.

If the selected analyzer filters the stop words "is" and "the", then for a document containing the string "blue is the sky", only the tokens "blue", "sky" are indexed, with position("sky") = 3 + position("blue"). Now, a phrase query "blue is the sky" would find that document, because the same analyzer filters the same stop words from that query. But the phrase query "blue sky" would not find that document because the position increment between "blue" and "sky" is only 1.

If this behavior does not fit the application needs, the query parser needs to be configured to not take position increments into account when generating phrase queries.

Note that a StopFilter MUST increment the position increment in order not to generate corrupt tokenstream graphs. Here is the logic used by StopFilter to increment positions when filtering out tokens:

  public TokenStream tokenStream(final String fieldName, Reader reader) {
    final TokenStream ts = someAnalyzer.tokenStream(fieldName, reader);
    TokenStream res = new TokenStream() {
      CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
      PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);

      public boolean incrementToken() throws IOException {
        int extraIncrement = 0;
        while (true) {
          boolean hasNext = ts.incrementToken();
          if (hasNext) {
            if (stopWords.contains(termAtt.toString())) {
              extraIncrement += posIncrAtt.getPositionIncrement(); // filter this word
              continue;
            } 
            if (extraIncrement>0) {
              posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement()+extraIncrement);
            }
          }
          return hasNext;
        }
      }
    };
    return res;
  }

A few more use cases for modifying position increments are:

  1. Inhibiting phrase and proximity matches in sentence boundaries – for this, a tokenizer that identifies a new sentence can add 1 to the position increment of the first token of the new sentence.
  2. Injecting synonyms – here, synonyms of a token should be added after that token, and their position increment should be set to 0. As result, all synonyms of a token would be considered to appear in exactly the same position as that token, and so would they be seen by phrase and proximity searches.

Token Position Length

By default, all tokens created by Analyzers and Tokenizers have a position length of one. This means that the token occupies a single position. This attribute is not indexed and thus not taken into account for positional queries, but is used by eg. suggesters.

The main use case for positions lengths is multi-word synonyms. With single-word synonyms, setting the position increment to 0 is enough to denote the fact that two words are synonyms, for example:

Termredmagenta
Position increment10

Given that position(magenta) = 0 + position(red), they are at the same position, so anything working with analyzers will return the exact same result if you replace "magenta" with "red" in the input. However, multi-word synonyms are more tricky. Let's say that you want to build a TokenStream where "IBM" is a synonym of "Internal Business Machines". Position increments are not enough anymore:

TermIBMInternationalBusinessMachines
Position increment1011

The problem with this token stream is that "IBM" is at the same position as "International" although it is a synonym with "International Business Machines" as a whole. Setting the position increment of "Business" and "Machines" to 0 wouldn't help as it would mean than "International" is a synonym of "Business". The only way to solve this issue is to make "IBM" span across 3 positions, this is where position lengths come to rescue.

TermIBMInternationalBusinessMachines
Position increment1011
Position length3111

This new attribute makes clear that "IBM" and "International Business Machines" start and end at the same positions.

How to not write corrupt token streams

There are a few rules to observe when writing custom Tokenizers and TokenFilters:

  • The first position increment must be > 0.
  • Positions must not go backward.
  • Tokens that have the same start position must have the same start offset.
  • Tokens that have the same end position (taking into account the position length) must have the same end offset.

Although these rules might seem easy to follow, problems can quickly happen when chaining badly implemented filters that play with positions and offsets, such as synonym or n-grams filters. Here are good practices for writing correct filters:

  • Token filters should not modify offsets. If you feel that your filter would need to modify offsets, then it should probably be implemented as a tokenizer.
  • Token filters should not insert positions. If a filter needs to add tokens, then they shoud all have a position increment of 0.
  • When they remove tokens, token filters should increment the position increment of the following token.
  • Token filters should preserve position lengths.

TokenStream API

"Flexible Indexing" summarizes the effort of making the Lucene indexer pluggable and extensible for custom index formats. A fully customizable indexer means that users will be able to store custom data structures on disk. Therefore an API is necessary that can transport custom types of data from the documents to the indexer.

Attribute and AttributeSource

Classes Attribute and AttributeSource serve as the basis upon which the analysis elements of "Flexible Indexing" are implemented. An Attribute holds a particular piece of information about a text token. For example, CharTermAttribute contains the term text of a token, and OffsetAttribute contains the start and end character offsets of a token. An AttributeSource is a collection of Attributes with a restriction: there may be only one instance of each attribute type. TokenStream now extends AttributeSource, which means that one can add Attributes to a TokenStream. Since TokenFilter extends TokenStream, all filters are also AttributeSources.

Lucene provides seven Attributes out of the box:

CharTermAttributeThe term text of a token. Implements CharSequence (providing methods length()
and charAt(), and allowing e.g. for direct use with regular expression
 Matchers)
and
 Appendable (allowing the term text to be appended to.)
OffsetAttributeThe start and end offset of a token in characters.
PositionIncrementAttributeSee above for detailed information about position increment.
PositionLengthAttributeThe number of positions occupied by a token.
PayloadAttributeThe payload that a Token can optionally have.
TypeAttributeThe type of the token. Default is 'word'.
FlagsAttributeOptional flags a token can have.
KeywordAttributeKeyword-aware TokenStreams/-Filters skip modification of tokens
that return true from this attribute's isKeyword() method.

Using the TokenStream API

There are a few important things to know in order to use the new API efficiently which are summarized here. You may want to walk through the example below first and come back to this section afterwards.
  1. Please keep in mind that an AttributeSource can only have one instance of a particular Attribute. Furthermore, if a chain of a TokenStream and multiple TokenFilters is used, then all TokenFilters in that chain share the Attributes with the TokenStream.

  2. Attribute instances are reused for all tokens of a document. Thus, a TokenStream/-Filter needs to update the appropriate Attribute(s) in incrementToken(). The consumer, commonly the Lucene indexer, consumes the data in the Attributes and then calls incrementToken() again until it returns false, which indicates that the end of the stream was reached. This means that in each call of incrementToken() a TokenStream/-Filter can safely overwrite the data in the Attribute instances.

  3. For performance reasons a TokenStream/-Filter should add/get Attributes during instantiation; i.e., create an attribute in the constructor and store references to it in an instance variable. Using an instance variable instead of calling addAttribute()/getAttribute() in incrementToken() will avoid attribute lookups for every token in the document.

  4. All methods in AttributeSource are idempotent, which means calling them multiple times always yields the same result. This is especially important to know for addAttribute(). The method takes the type (Class) of an Attribute as an argument and returns aninstance. If an Attribute of the same type was previously added, then the already existing instance is returned, otherwise a new instance is created and returned. Therefore TokenStreams/-Filters can safely call addAttribute() with the same Attribute type multiple times. Even consumers of TokenStreams should normally call addAttribute() instead of getAttribute(), because it would not fail if the TokenStream does not have this Attribute (getAttribute() would throw an IllegalArgumentException, if the Attribute is missing). More advanced code could simply check with hasAttribute(), if a TokenStream has it, and may conditionally leave out processing for extra performance.

Example

In this example we will create a WhiteSpaceTokenizer and use a LengthFilter to suppress all words that have only two or fewer characters. The LengthFilter is part of the Lucene core and its implementation will be explained here to illustrate the usage of the TokenStream API.

Then we will develop a custom Attribute, a PartOfSpeechAttribute, and add another filter to the chain which utilizes the new custom attribute, and call it PartOfSpeechTaggingFilter.

Whitespace tokenization

public class MyAnalyzer extends Analyzer {

  private Version matchVersion;
  
  public MyAnalyzer(Version matchVersion) {
    this.matchVersion = matchVersion;
  }

  @Override
  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
    return new TokenStreamComponents(new WhitespaceTokenizer(matchVersion, reader));
  }
  
  public static void main(String[] args) throws IOException {
    // text to tokenize
    final String text = "This is a demo of the TokenStream API";
    
    Version matchVersion = Version.LUCENE_XY; // Substitute desired Lucene version for XY
    MyAnalyzer analyzer = new MyAnalyzer(matchVersion);
    TokenStream stream = analyzer.tokenStream("field", new StringReader(text));
    
    // get the CharTermAttribute from the TokenStream
    CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);

    try {
      stream.reset();
    
      // print all tokens until stream is exhausted
      while (stream.incrementToken()) {
        System.out.println(termAtt.toString());
      }
    
      stream.end();
    } finally {
      stream.close();
    }
  }
}
In this easy example a simple white space tokenization is performed. In main() a loop consumes the stream and prints the term text of the tokens by accessing the CharTermAttribute that the WhitespaceTokenizer provides. Here is the output:
This
is
a
demo
of
the
new
TokenStream
API

Adding a LengthFilter

We want to suppress all tokens that have 2 or less characters. We can do that easily by adding a LengthFilter to the chain. Only the createComponents() method in our analyzer needs to be changed:
  @Override
  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
    final Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
    TokenStream result = new LengthFilter(true, source, 3, Integer.MAX_VALUE);
    return new TokenStreamComponents(source, result);
  }
Note how now only words with 3 or more characters are contained in the output:
This
demo
the
new
TokenStream
API
Now let's take a look how the LengthFilter is implemented:
public final class LengthFilter extends FilteringTokenFilter {

  private final int min;
  private final int max;
  
  private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);

  /**
   * Create a new LengthFilter. This will filter out tokens whose
   * CharTermAttribute is either too short
   * (< min) or too long (> max).
   * @param version the Lucene match version
   * @param in      the TokenStream to consume
   * @param min     the minimum length
   * @param max     the maximum length
   */
  public LengthFilter(Version version, TokenStream in, int min, int max) {
    super(version, in);
    this.min = min;
    this.max = max;
  }

  @Override
  public boolean accept() {
    final int len = termAtt.length();
    return (len >= min && len <= max);
  }

}

In LengthFilter, the CharTermAttribute is added and stored in the instance variable termAtt. Remember that there can only be a single instance of CharTermAttribute in the chain, so in our example the addAttribute() call in LengthFilter returns the CharTermAttribute that the WhitespaceTokenizer already added.

The tokens are retrieved from the input stream in FilteringTokenFilter's incrementToken() method (see below), which calls LengthFilter's accept() method. By looking at the term text in the CharTermAttribute, the length of the term can be determined and tokens that are either too short or too long are skipped. Note how accept() can efficiently access the instance variable; no attribute lookup is necessary. The same is true for the consumer, which can simply use local references to the Attributes.

LengthFilter extends FilteringTokenFilter:

public abstract class FilteringTokenFilter extends TokenFilter {

  private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);

  /**
   * Create a new FilteringTokenFilter.
   * @param in      the TokenStream to consume
   */
  public FilteringTokenFilter(Version version, TokenStream in) {
    super(in);
  }

  /** Override this method and return if the current input token should be returned by incrementToken. */
  protected abstract boolean accept() throws IOException;

  @Override
  public final boolean incrementToken() throws IOException {
    int skippedPositions = 0;
    while (input.incrementToken()) {
      if (accept()) {
        if (skippedPositions != 0) {
          posIncrAtt.setPositionIncrement(posIncrAtt.getPositionIncrement() + skippedPositions);
        }
        return true;
      }
      skippedPositions += posIncrAtt.getPositionIncrement();
    }
    // reached EOS -- return false
    return false;
  }

  @Override
  public void reset() throws IOException {
    super.reset();
  }

}

Adding a custom Attribute

Now we're going to implement our own custom Attribute for part-of-speech tagging and call it consequently PartOfSpeechAttribute. First we need to define the interface of the new Attribute:
  public interface PartOfSpeechAttribute extends Attribute {
    public static enum PartOfSpeech {
      Noun, Verb, Adjective, Adverb, Pronoun, Preposition, Conjunction, Article, Unknown
    }
  
    public void setPartOfSpeech(PartOfSpeech pos);
  
    public PartOfSpeech getPartOfSpeech();
  }

Now we also need to write the implementing class. The name of that class is important here: By default, Lucene checks if there is a class with the name of the Attribute with the suffix 'Impl'. In this example, we would consequently call the implementing classPartOfSpeechAttributeImpl.

This should be the usual behavior. However, there is also an expert-API that allows changing these naming conventions: AttributeSource.AttributeFactory. The factory accepts an Attribute interface as argument and returns an actual instance. You can implement your own factory if you need to change the default behavior.

Now here is the actual class that implements our new Attribute. Notice that the class has to extend AttributeImpl:

public final class PartOfSpeechAttributeImpl extends AttributeImpl 
                                  implements PartOfSpeechAttribute {
  
  private PartOfSpeech pos = PartOfSpeech.Unknown;
  
  public void setPartOfSpeech(PartOfSpeech pos) {
    this.pos = pos;
  }
  
  public PartOfSpeech getPartOfSpeech() {
    return pos;
  }

  @Override
  public void clear() {
    pos = PartOfSpeech.Unknown;
  }

  @Override
  public void copyTo(AttributeImpl target) {
    ((PartOfSpeechAttribute) target).setPartOfSpeech(pos);
  }
}

This is a simple Attribute implementation has only a single variable that stores the part-of-speech of a token. It extends the AttributeImpl class and therefore implements its abstract methods clear() and copyTo(). Now we need a TokenFilter that can set this new PartOfSpeechAttribute for each token. In this example we show a very naive filter that tags every word with a leading upper-case letter as a 'Noun' and all other words as 'Unknown'.

  public static class PartOfSpeechTaggingFilter extends TokenFilter {
    PartOfSpeechAttribute posAtt = addAttribute(PartOfSpeechAttribute.class);
    CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
    
    protected PartOfSpeechTaggingFilter(TokenStream input) {
      super(input);
    }
    
    public boolean incrementToken() throws IOException {
      if (!input.incrementToken()) {return false;}
      posAtt.setPartOfSpeech(determinePOS(termAtt.buffer(), 0, termAtt.length()));
      return true;
    }
    
    // determine the part of speech for the given term
    protected PartOfSpeech determinePOS(char[] term, int offset, int length) {
      // naive implementation that tags every uppercased word as noun
      if (length > 0 && Character.isUpperCase(term[0])) {
        return PartOfSpeech.Noun;
      }
      return PartOfSpeech.Unknown;
    }
  }

Just like the LengthFilter, this new filter stores references to the attributes it needs in instance variables. Notice how you only need to pass in the interface of the new Attribute and instantiating the correct class is automatically taken care of.

Now we need to add the filter to the chain in MyAnalyzer:

  @Override
  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
    final Tokenizer source = new WhitespaceTokenizer(matchVersion, reader);
    TokenStream result = new LengthFilter(true, source, 3, Integer.MAX_VALUE);
    result = new PartOfSpeechTaggingFilter(result);
    return new TokenStreamComponents(source, result);
  }
Now let's look at the output:
This
demo
the
new
TokenStream
API
Apparently it hasn't changed, which shows that adding a custom attribute to a TokenStream/Filter chain does not affect any existing consumers, simply because they don't know the new Attribute. Now let's change the consumer to make use of the new PartOfSpeechAttribute and print it out:
  public static void main(String[] args) throws IOException {
    // text to tokenize
    final String text = "This is a demo of the TokenStream API";
    
    MyAnalyzer analyzer = new MyAnalyzer();
    TokenStream stream = analyzer.tokenStream("field", new StringReader(text));
    
    // get the CharTermAttribute from the TokenStream
    CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class);
    
    // get the PartOfSpeechAttribute from the TokenStream
    PartOfSpeechAttribute posAtt = stream.addAttribute(PartOfSpeechAttribute.class);

    try {
      stream.reset();

      // print all tokens until stream is exhausted
      while (stream.incrementToken()) {
        System.out.println(termAtt.toString() + ": " + posAtt.getPartOfSpeech());
      }
    
      stream.end();
    } finally {
      stream.close();
    }
  }
The change that was made is to get the PartOfSpeechAttribute from the TokenStream and print out its contents in the while loop that consumes the stream. Here is the new output:
This: Noun
demo: Unknown
the: Unknown
new: Unknown
TokenStream: Noun
API: Noun
Each word is now followed by its assigned PartOfSpeech tag. Of course this is a naive part-of-speech tagging. The word 'This' should not even be tagged as noun; it is only spelled capitalized because it is the first word of a sentence. Actually this is a good opportunity for an exercise. To practice the usage of the new API the reader could now write an Attribute and TokenFilter that can specify for each word if it was the first token of a sentence or not. Then the PartOfSpeechTaggingFilter can make use of this knowledge and only tag capitalized words as nouns if not the first word of a sentence (we know, this is still not a correct behavior, but hey, it's a good exercise). As a small hint, this is how the new Attribute class could begin:
  public class FirstTokenOfSentenceAttributeImpl extends AttributeImpl
                              implements FirstTokenOfSentenceAttribute {
    
    private boolean firstToken;
    
    public void setFirstToken(boolean firstToken) {
      this.firstToken = firstToken;
    }
    
    public boolean getFirstToken() {
      return firstToken;
    }

    @Override
    public void clear() {
      firstToken = false;
    }

  ...

Adding a CharFilter chain

Analyzers take Java Readers as input. Of course you can wrap your Readers with FilterReaders to manipulate content, but this would have the big disadvantage that character offsets might be inconsistent with your original text.

CharFilter is designed to allow you to pre-process input like a FilterReader would, but also preserve the original offsets associated with those characters. This way mechanisms like highlighting still work correctly. CharFilters can be chained.

Example:

public class MyAnalyzer extends Analyzer {

  @Override
  protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
    return new TokenStreamComponents(new MyTokenizer(reader));
  }
  
  @Override
  protected Reader initReader(String fieldName, Reader reader) {
    // wrap the Reader in a CharFilter chain.
    return new SecondCharFilter(new FirstCharFilter(reader));
  }
}


신고
크리에이티브 커먼즈 라이선스
Creative Commons License
Trackback 0 : Comment 0

티스토리 툴바