lucene搜索之拼写检查和相似度查询提示(spellcheck)

suggest应用场景

用户的输入行为是不确定的,而我们在写程序的时候总是想让用户按照指定的内容或指定格式的内容进行搜索,这里就要进行人工干预用户输入的搜索条件了;我们在用百度谷歌等搜索引擎的时候经常会看到按键放下的时候直接会提示用户是否想搜索某些相关的内容,恰好lucene在开发的时候想到了这一点,lucene提供的suggest包正是用来解决上述问题的。

suggest包联想词相关介绍

suggest包提供了lucene的自动补全或者拼写检查的支持;

拼写检查相关的类在org.apache.lucene.search.spell包下;

联想相关的在org.apache.lucene.search.suggest包下;

基于联想词分词相关的类在org.apache.lucene.search.suggest.analyzing包下;

拼写检查原理

  • Lucene的拼写检查由org.apache.lucene.search.spell.SpellChecker类提供支持;
  • SpellChecker设置了默认精度0.5,如果我们需要细粒度的支持可以通过调用setAccuracy(float accuracy)来设定;
  • spellChecker会将外部来源的词进行索引;

这些来源包括:

           DocumentDictionary查询document中的field对应的值;

           FileDictionary基于一个文本文件的Directionary,每行一项,词组之间以"\t" TAB分隔符进行,每项中不能含有两个以上的分隔符;

           HighFrequencyDictionary从原有的索引文件中读取某个term的值,并按照出现次数检查;

           LuceneDictionary也是从原有索引文件中读取某个term的值,但是不检查出现次数;

扫描二维码关注公众号,回复: 88080 查看本文章

           PlainTextDictionary从文本中读取内容,按行读取,没有分隔符;

 其索引的原理如下:

  1. 对索引过程加syschronized同步;
  2. 检查Spellchecker是否已经关闭,如果关闭,抛出异常,提示内容为:Spellchecker has been closed;
  3. 对外部来源的索引进行遍历,统计被遍历的词的长度,如果长度小于三,忽略该词,反之构建document对象并索引到本地文件,创建索引的时候会对每个单词进行详细拆分(对应addGram方法),其执行过程如下所示

[java] view plain copy

  1. /** 
  2.    * Indexes the data from the given {@link Dictionary}. 
  3.    * @param dict Dictionary to index 
  4.    * @param config {@link IndexWriterConfig} to use 
  5.    * @param fullMerge whether or not the spellcheck index should be fully merged 
  6.    * @throws AlreadyClosedException if the Spellchecker is already closed 
  7.    * @throws IOException If there is a low-level I/O error. 
  8.    */  
  9.   public final void indexDictionary(Dictionary dict, IndexWriterConfig config, boolean fullMerge) throws IOException {  
  10.     synchronized (modifyCurrentIndexLock) {  
  11.       ensureOpen();  
  12.       final Directory dir = this.spellIndex;  
  13.       final IndexWriter writer = new IndexWriter(dir, config);  
  14.       IndexSearcher indexSearcher = obtainSearcher();  
  15.       final List<TermsEnum> termsEnums = new ArrayList<>();  
  16.   
  17.       final IndexReader reader = searcher.getIndexReader();  
  18.       if (reader.maxDoc() > 0) {  
  19.         for (final LeafReaderContext ctx : reader.leaves()) {  
  20.           Terms terms = ctx.reader().terms(F_WORD);  
  21.           if (terms != null)  
  22.             termsEnums.add(terms.iterator(null));  
  23.         }  
  24.       }  
  25.         
  26.       boolean isEmpty = termsEnums.isEmpty();  
  27.   
  28.       try {   
  29.         BytesRefIterator iter = dict.getEntryIterator();  
  30.         BytesRef currentTerm;  
  31.           
  32.         terms: while ((currentTerm = iter.next()) != null) {  
  33.     
  34.           String word = currentTerm.utf8ToString();  
  35.           int len = word.length();  
  36.           if (len < 3) {  
  37.             continue; // too short we bail but "too long" is fine...  
  38.           }  
  39.     
  40.           if (!isEmpty) {  
  41.             for (TermsEnum te : termsEnums) {  
  42.               if (te.seekExact(currentTerm)) {  
  43.                 continue terms;  
  44.               }  
  45.             }  
  46.           }  
  47.     
  48.           // ok index the word  
  49.           Document doc = createDocument(word, getMin(len), getMax(len));  
  50.           writer.addDocument(doc);  
  51.         }  
  52.       } finally {  
  53.         releaseSearcher(indexSearcher);  
  54.       }  
  55.       if (fullMerge) {  
  56.         writer.forceMerge(1);  
  57.       }  
  58.       // close writer  
  59.       writer.close();  
  60.       // TODO: this isn't that great, maybe in the future SpellChecker should take  
  61.       // IWC in its ctor / keep its writer open?  
  62.         
  63.       // also re-open the spell index to see our own changes when the next suggestion  
  64.       // is fetched:  
  65.       swapSearcher(dir);  
  66.     }  
  67.   }  

对词语进行遍历拆分的方法为addGram,其实现为:

查看代码可知,联想词的索引不仅关注每个词的起始位置,也关注其倒数的位置;

  • 联想词查询的时候,先判断grams里边是否包含有待查询的词拆分后的内容,如果有放到结果SuggestWordQueue中,最终结果为遍历SuggestWordQueue得来的String[],其代码实现如下:[java] view plain copy
    1. public String[] suggestSimilar(String word, int numSug, IndexReader ir,  
    2.       String field, SuggestMode suggestMode, float accuracy) throws IOException {  
    3.     // obtainSearcher calls ensureOpen  
    4.     final IndexSearcher indexSearcher = obtainSearcher();  
    5.     try {  
    6.       if (ir == null || field == null) {  
    7.         suggestMode = SuggestMode.SUGGEST_ALWAYS;  
    8.       }  
    9.       if (suggestMode == SuggestMode.SUGGEST_ALWAYS) {  
    10.         ir = null;  
    11.         field = null;  
    12.       }  
    13.   
    14.       final int lengthWord = word.length();  
    15.   
    16.       final int freq = (ir != null && field != null) ? ir.docFreq(new Term(field, word)) : 0;  
    17.       final int goalFreq = suggestMode==SuggestMode.SUGGEST_MORE_POPULAR ? freq : 0;  
    18.       // if the word exists in the real index and we don't care for word frequency, return the word itself  
    19.       if (suggestMode==SuggestMode.SUGGEST_WHEN_NOT_IN_INDEX && freq > 0) {  
    20.         return new String[] { word };  
    21.       }  
    22.   
    23.       BooleanQuery query = new BooleanQuery();  
    24.       String[] grams;  
    25.       String key;  
    26.   
    27.       for (int ng = getMin(lengthWord); ng <= getMax(lengthWord); ng++) {  
    28.   
    29.         key = "gram" + ng; // form key  
    30.   
    31.         grams = formGrams(word, ng); // form word into ngrams (allow dups too)  
    32.   
    33.         if (grams.length == 0) {  
    34.           continue; // hmm  
    35.         }  
    36.   
    37.         if (bStart > 0) { // should we boost prefixes?  
    38.           add(query, "start" + ng, grams[0], bStart); // matches start of word  
    39.   
    40.         }  
    41.         if (bEnd > 0) { // should we boost suffixes  
    42.           add(query, "end" + ng, grams[grams.length - 1], bEnd); // matches end of word  
    43.   
    44.         }  
    45.         for (int i = 0; i < grams.length; i++) {  
    46.           add(query, key, grams[i]);  
    47.         }  
    48.       }  
    49.   
    50.       int maxHits = 10 * numSug;  
    51.   
    52.   //    System.out.println("Q: " + query);  
    53.       ScoreDoc[] hits = indexSearcher.search(query, maxHits).scoreDocs;  
    54.   //    System.out.println("HITS: " + hits.length());  
    55.       SuggestWordQueue sugQueue = new SuggestWordQueue(numSug, comparator);  
    56.   
    57.       // go thru more than 'maxr' matches in case the distance filter triggers  
    58.       int stop = Math.min(hits.length, maxHits);  
    59.       SuggestWord sugWord = new SuggestWord();  
    60.       for (int i = 0; i < stop; i++) {  
    61.   
    62.         sugWord.string = indexSearcher.doc(hits[i].doc).get(F_WORD); // get orig word  
    63.   
    64.         // don't suggest a word for itself, that would be silly  
    65.         if (sugWord.string.equals(word)) {  
    66.           continue;  
    67.         }  
    68.   
    69.         // edit distance  
    70.         sugWord.score = sd.getDistance(word,sugWord.string);  
    71.         if (sugWord.score < accuracy) {  
    72.           continue;  
    73.         }  
    74.   
    75.         if (ir != null && field != null) { // use the user index  
    76.           sugWord.freq = ir.docFreq(new Term(field, sugWord.string)); // freq in the index  
    77.           // don't suggest a word that is not present in the field  
    78.           if ((suggestMode==SuggestMode.SUGGEST_MORE_POPULAR && goalFreq > sugWord.freq) || sugWord.freq < 1) {  
    79.             continue;  
    80.           }  
    81.         }  
    82.         sugQueue.insertWithOverflow(sugWord);  
    83.         if (sugQueue.size() == numSug) {  
    84.           // if queue full, maintain the minScore score  
    85.           accuracy = sugQueue.top().score;  
    86.         }  
    87.         sugWord = new SuggestWord();  
    88.       }  
    89.   
    90.       // convert to array string  
    91.       String[] list = new String[sugQueue.size()];  
    92.       for (int i = sugQueue.size() - 1; i >= 0; i--) {  
    93.         list[i] = sugQueue.pop().string;  
    94.       }  
    95.   
    96.       return list;  
    97.     } finally {  
    98.       releaseSearcher(indexSearcher);  
    99.     }  
    100.   }  

编程实践

以下是我根据FileDirectory相关描述编写的一个测试程序

[java] view plain copy

  1. package com.lucene.search;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.nio.file.Paths;  
  7.   
  8. import org.apache.lucene.analysis.Analyzer;  
  9. import org.apache.lucene.index.IndexWriterConfig;  
  10. import org.apache.lucene.index.IndexWriterConfig.OpenMode;  
  11. import org.apache.lucene.search.spell.SpellChecker;  
  12. import org.apache.lucene.search.suggest.FileDictionary;  
  13. import org.apache.lucene.store.Directory;  
  14. import org.apache.lucene.store.FSDirectory;  
  15. import org.wltea.analyzer.lucene.IKAnalyzer;  
  16.   
  17.   
  18.   
  19. public class SuggestUtil {  
  20.     public static void main(String[] args) {  
  21.         Directory spellIndexDirectory;  
  22.         try {  
  23.             spellIndexDirectory = FSDirectory.open(Paths.get("suggest", new String[0]));  
  24.               
  25.             SpellChecker spellchecker = new SpellChecker(spellIndexDirectory );  
  26.             Analyzer analyzer = new IKAnalyzer(true);  
  27.             IndexWriterConfig config = new IndexWriterConfig(analyzer);  
  28.             config.setOpenMode(OpenMode.CREATE_OR_APPEND);  
  29.             spellchecker.setAccuracy(0f);  
  30.             //HighFrequencyDictionary dire = new HighFrequencyDictionary(reader, field, thresh)  
  31.             spellchecker.indexDictionary(new FileDictionary(new FileInputStream(new File("D:\\hadoop\\lucene_suggest\\src\\suggest.txt"))),config,false);  
  32.             String[] similars = spellchecker.suggestSimilar("中国", 10);  
  33.             for (String similar : similars) {  
  34.                 System.out.println(similar);  
  35.             }  
  36.             spellIndexDirectory.close();  
  37.             spellchecker.close();  
  38.         } catch (IOException e) {  
  39.             // TODO Auto-generated catch block  
  40.             e.printStackTrace();  
  41.         }  
  42.                   
  43.   
  44.     }  
  45. }  


 

其中,我用的suggest.txt内容为:

[plain] view plain copy

  1. 中国人民    100  
  2. 奔驰3 101  
  3. 奔驰中国    102  
  4. 奔驰S级    103  
  5. 奔驰A级    104  
  6. 奔驰C级    105  

测试结果为:

[plain] view plain copy

  1. 中国人民  
  2. 奔驰中国  

猜你喜欢

转载自my.oschina.net/xiaominmin/blog/1796665