標籤:搜尋 全文檢索索引 lucene
今天我們實現一個簡單的分詞器,僅僅做示範使用功能如下:
1、分詞按照空格、橫杠、點號進行拆分;
2、實現hi與hello的同義字查詢功能;
3、實現hi與hello同義字的高亮顯示;
MyAnalyzer實現代碼:
public class MyAnalyzer extends Analyzer {private int analyzerType;public MyAnalyzer(int type) {super();analyzerType = type;}@Overrideprotected TokenStreamComponents createComponents(String fieldName, Reader reader) {MyTokenizer tokenizer = new MyTokenizer(fieldName, reader, analyzerType);return new TokenStreamComponents(tokenizer);}}
MyTokenizer實現代碼:
public class MyTokenizer extends Tokenizer {public class WordUnit{WordUnit(String word, int start, int length){this.word = word;this.start = start;this.length = length;//System.out.println("\tWordUnit: " + word + "|" + start + "|" + length);}String word;int start;int length;}private int analyzerType;private int endPosition;private Iterator<WordUnit> it;private ArrayList<WordUnit> words;private final CharTermAttribute termAtt;private final OffsetAttribute offsetAtt;public MyTokenizer(String fieldName, Reader in, int type) {super(in);it = null;endPosition = 0;analyzerType = type;offsetAtt = addAttribute(OffsetAttribute.class);termAtt = addAttribute(CharTermAttribute.class);addAttribute(PayloadAttribute.class);}@Overridepublic boolean incrementToken() throws IOException {clearAttributes();char[] inputBuf = new char[1024];if(it == null) {int bufSize = input.read(inputBuf);if(bufSize <= 0) return false;int beginIndex = 0;int endIndex = 0;words = new ArrayList<WordUnit>();for(endIndex = 0; endIndex < bufSize; endIndex++) {if(inputBuf[endIndex] != '-' && inputBuf[endIndex] != ' ' && inputBuf[endIndex] != '.') continue;addWord(inputBuf, beginIndex, endIndex);beginIndex = endIndex + 1;}addWord(inputBuf, beginIndex, endIndex);//add the lastif(words.isEmpty()) return false;it = words.iterator();}if(it != null && it.hasNext()){WordUnit word = it.next();termAtt.append(word.word);termAtt.setLength(word.word.length());endPosition = word.start + word.length;offsetAtt.setOffset(word.start, endPosition);return true;}return false;}@Overridepublic void reset() throws IOException {super.reset();it = null;endPosition = 0;}@Overridepublic final void end() {int finalOffset = correctOffset(this.endPosition);offsetAtt.setOffset(finalOffset, finalOffset);}private void addWord(char[] inputBuf, int begin, int end){if(end <= begin) return;String word = new String(inputBuf, begin, end - begin);words.add(new WordUnit(word, begin, end - begin)); if(analyzerType == 0 && word.equals("hi")) words.add(new WordUnit("hello", begin, 2)); if(analyzerType == 0 && word.equals("hello")) words.add(new WordUnit("hi", begin, 5));}}
索引的時候分詞器類型:analyzerType=0;
搜尋的時候分詞器類型:analyzerType=1;
高亮的時候分詞器類型:analyzerType=0;
搜尋hello時的效果如下:
Score doc 0 hightlight to: look <em>hello</em> onScore doc 1 hightlight to: I am <em>hi</em> China Chinese
可以看到含有hi的文檔也被搜尋出來,同樣也會高亮。
Lucene實現自訂分詞器(同義字查詢與高亮)