自定义Solr TokenFilter引理器

时间:2013-02-18 12:25:41

标签: java solr

我正在尝试编写一个简单的Solr lemmatizer用于字段类型,但我似乎无法找到有关编写TokenFilter的任何信息,所以我有点迷失。这是我到目前为止的代码。

import java.io.IOException;
import java.util.List;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class FooFilter extends TokenFilter {

    private static final Logger log = LoggerFactory.getLogger(FooFilter.class);
    private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
    private final PositionIncrementAttribute posAtt = addAttribute(PositionIncrementAttribute.class);

    public FooFilter(TokenStream input) {
        super(input);
    }

    @Override
    public boolean incrementToken() throws IOException {
        if (!input.incrementToken()) {
            return false;
        }

        char termBuffer[] = termAtt.buffer();
        List<String> allForms = Lemmatize.getAllForms(new String(termBuffer));
        if (allForms.size() > 0) {
            for (String word : allForms) {
                // Now what?
            }
        }

        return true;
    }
}

1 个答案:

答案 0 :(得分:4)

接下来,您想要用replaceappend 当前令牌termAtt

示例替换语义

termAtt.setEmpty();
termAtt.copyBuffer(word.toCharArray(), 0, word.length());

添加新令牌的示例语义

对于要添加的每个标记,必须设置CharTermAttribute属性并使incrementToken例程返回true。

private List<String> extraTokens = ...
public boolean incrementToken() { 
  if (input.incrementToken()){ 
    // ... 
    return true; 
  } else if (!extraTokens.isEmtpy()) { 
    // set the added token and return true
    termAtt.setTerm(extraTokens.remove(0)); 
    return true; 
  } 
  return false; 
}