2008-09-23 14 views
46

मैं ल्यूसीन में पूछताछ ऑटो-समापन/सुझाव करने का एक तरीका ढूंढ रहा हूं। मैंने थोड़ी देर के आसपास गुगल किया है और थोड़ा सा खेला है, लेकिन मैंने देखा है कि सभी उदाहरण Solr में फ़िल्टर स्थापित करने लगते हैं। हम सोलर का उपयोग नहीं करते हैं और निकट भविष्य में सोलर का उपयोग करने की योजना नहीं बना रहे हैं, और सोलर स्पष्ट रूप से ल्यूसीन के आसपास लपेट रहा है, इसलिए मुझे लगता है कि ऐसा करने का एक तरीका होना चाहिए!ल्यूसीन में पूछताछ ऑटो-समापन/सुझाव कैसे करें?

मैंने एजेंग्रामफिल्टर का उपयोग करने में देखा है, और मुझे एहसास है कि मुझे इंडेक्स फ़ील्ड पर फ़िल्टर चलाने और टोकन प्राप्त करना होगा और फिर इनपुट क्वेरी के विरुद्ध उनकी तुलना करें ... मैं बस संघर्ष कर रहा हूं दोनों के बीच कनेक्शन को थोड़ा सा कोड बनाओ, इसलिए मदद की बहुत सराहना की जाती है!

जो मैं ढूंढ रहा हूं उस पर स्पष्ट होने के लिए (मुझे एहसास हुआ कि मैं अत्यधिक स्पष्ट नहीं था, माफ करना) - मैं एक ऐसे समाधान की तलाश में हूं जहां एक शब्द की खोज करते समय, यह सुझाए गए एक सूची को वापस कर देगा प्रश्नों। खोज क्षेत्र में 'इंटर' टाइप करते समय, यह 'इंटरनेट', 'अंतर्राष्ट्रीय' इत्यादि जैसे सुझाए गए प्रश्नों की एक सूची के साथ वापस आ जाएगा।

+0

लुसीन के पास अब विशेष रूप से स्वत: पूर्णता/सुझाव करने के लिए कुछ कोड है। Http://stackoverflow.com/questions/24968697/how-to-implements-auto-suggest-using-lucenes-new-analyzinginfixsuggester-api/25301811#25301811 एक उत्तर के लिए इसका उपयोग करने का वर्णन करने के लिए देखें। –

उत्तर

35

@Alexandre Victoor के जवाब के आधार पर, मैं एक छोटे से योगदान पैकेज में Lucene वर्तनी-जांचकर्ता (और का उपयोग कर LuceneDictionary यह में शामिल है) के आधार पर वर्ग लिखा है कि मैं वास्तव में क्या चाहते हैं।

यह एक एकल स्रोत इंडेक्स से एक फ़ील्ड के साथ पुनः अनुक्रमणित करने की अनुमति देता है, और शर्तों के लिए सुझाव प्रदान करता है। परिणामों को मूल अनुक्रमणिका में उस शब्द के साथ मेल खाने वाले दस्तावेज़ों की संख्या द्वारा क्रमबद्ध किया जाता है, इसलिए अधिक लोकप्रिय शब्द पहले दिखाई देते हैं। बहुत अच्छी तरह से काम करने के लिए :)

import java.io.IOException; 
import java.io.Reader; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 

import org.apache.lucene.analysis.Analyzer; 
import org.apache.lucene.analysis.ISOLatin1AccentFilter; 
import org.apache.lucene.analysis.LowerCaseFilter; 
import org.apache.lucene.analysis.StopFilter; 
import org.apache.lucene.analysis.TokenStream; 
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter; 
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side; 
import org.apache.lucene.analysis.standard.StandardFilter; 
import org.apache.lucene.analysis.standard.StandardTokenizer; 
import org.apache.lucene.document.Document; 
import org.apache.lucene.document.Field; 
import org.apache.lucene.index.CorruptIndexException; 
import org.apache.lucene.index.IndexReader; 
import org.apache.lucene.index.IndexWriter; 
import org.apache.lucene.index.Term; 
import org.apache.lucene.search.IndexSearcher; 
import org.apache.lucene.search.Query; 
import org.apache.lucene.search.ScoreDoc; 
import org.apache.lucene.search.Sort; 
import org.apache.lucene.search.TermQuery; 
import org.apache.lucene.search.TopDocs; 
import org.apache.lucene.search.spell.LuceneDictionary; 
import org.apache.lucene.store.Directory; 
import org.apache.lucene.store.FSDirectory; 

/** 
* Search term auto-completer, works for single terms (so use on the last term 
* of the query). 
* <p> 
* Returns more popular terms first. 
* 
* @author Mat Mannion, [email protected] 
*/ 
public final class Autocompleter { 

    private static final String GRAMMED_WORDS_FIELD = "words"; 

    private static final String SOURCE_WORD_FIELD = "sourceWord"; 

    private static final String COUNT_FIELD = "count"; 

    private static final String[] ENGLISH_STOP_WORDS = { 
    "a", "an", "and", "are", "as", "at", "be", "but", "by", 
    "for", "i", "if", "in", "into", "is", 
    "no", "not", "of", "on", "or", "s", "such", 
    "t", "that", "the", "their", "then", "there", "these", 
    "they", "this", "to", "was", "will", "with" 
    }; 

    private final Directory autoCompleteDirectory; 

    private IndexReader autoCompleteReader; 

    private IndexSearcher autoCompleteSearcher; 

    public Autocompleter(String autoCompleteDir) throws IOException { 
     this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir, 
       null); 

     reOpenReader(); 
    } 

    public List<String> suggestTermsFor(String term) throws IOException { 
     // get the top 5 terms for query 
     Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term)); 
     Sort sort = new Sort(COUNT_FIELD, true); 

     TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort); 
     List<String> suggestions = new ArrayList<String>(); 
     for (ScoreDoc doc : docs.scoreDocs) { 
      suggestions.add(autoCompleteReader.document(doc.doc).get(
        SOURCE_WORD_FIELD)); 
     } 

     return suggestions; 
    } 

    @SuppressWarnings("unchecked") 
    public void reIndex(Directory sourceDirectory, String fieldToAutocomplete) 
      throws CorruptIndexException, IOException { 
     // build a dictionary (from the spell package) 
     IndexReader sourceReader = IndexReader.open(sourceDirectory); 

     LuceneDictionary dict = new LuceneDictionary(sourceReader, 
       fieldToAutocomplete); 

     // code from 
     // org.apache.lucene.search.spell.SpellChecker.indexDictionary(
     // Dictionary) 
     IndexReader.unlock(autoCompleteDirectory); 

     // use a custom analyzer so we can do EdgeNGramFiltering 
     IndexWriter writer = new IndexWriter(autoCompleteDirectory, 
     new Analyzer() { 
      public TokenStream tokenStream(String fieldName, 
        Reader reader) { 
       TokenStream result = new StandardTokenizer(reader); 

       result = new StandardFilter(result); 
       result = new LowerCaseFilter(result); 
       result = new ISOLatin1AccentFilter(result); 
       result = new StopFilter(result, 
        ENGLISH_STOP_WORDS); 
       result = new EdgeNGramTokenFilter(
        result, Side.FRONT,1, 20); 

       return result; 
      } 
     }, true); 

     writer.setMergeFactor(300); 
     writer.setMaxBufferedDocs(150); 

     // go through every word, storing the original word (incl. n-grams) 
     // and the number of times it occurs 
     Map<String, Integer> wordsMap = new HashMap<String, Integer>(); 

     Iterator<String> iter = (Iterator<String>) dict.getWordsIterator(); 
     while (iter.hasNext()) { 
      String word = iter.next(); 

      int len = word.length(); 
      if (len < 3) { 
       continue; // too short we bail but "too long" is fine... 
      } 

      if (wordsMap.containsKey(word)) { 
       throw new IllegalStateException(
         "This should never happen in Lucene 2.3.2"); 
       // wordsMap.put(word, wordsMap.get(word) + 1); 
      } else { 
       // use the number of documents this word appears in 
       wordsMap.put(word, sourceReader.docFreq(new Term(
         fieldToAutocomplete, word))); 
      } 
     } 

     for (String word : wordsMap.keySet()) { 
      // ok index the word 
      Document doc = new Document(); 
      doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES, 
        Field.Index.UN_TOKENIZED)); // orig term 
      doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES, 
        Field.Index.TOKENIZED)); // grammed 
      doc.add(new Field(COUNT_FIELD, 
        Integer.toString(wordsMap.get(word)), Field.Store.NO, 
        Field.Index.UN_TOKENIZED)); // count 

      writer.addDocument(doc); 
     } 

     sourceReader.close(); 

     // close writer 
     writer.optimize(); 
     writer.close(); 

     // re-open our reader 
     reOpenReader(); 
    } 

    private void reOpenReader() throws CorruptIndexException, IOException { 
     if (autoCompleteReader == null) { 
      autoCompleteReader = IndexReader.open(autoCompleteDirectory); 
     } else { 
      autoCompleteReader.reopen(); 
     } 

     autoCompleteSearcher = new IndexSearcher(autoCompleteReader); 
    } 

    public static void main(String[] args) throws Exception { 
     Autocompleter autocomplete = new Autocompleter("/index/autocomplete"); 

     // run this to re-index from the current index, shouldn't need to do 
     // this very often 
     // autocomplete.reIndex(FSDirectory.getDirectory("/index/live", null), 
     // "content"); 

     String term = "steve"; 

     System.out.println(autocomplete.suggestTermsFor(term)); 
     // prints [steve, steven, stevens, stevenson, stevenage] 
    } 

} 
+2

ध्यान दें कि यह लुसीन के पुराने संस्करण के लिए बनाया गया था। वर्तमान संस्करण (4.4.0) में विश्लेषक वर्ग पर लागू करने के लिए सार विधि बनाई गई है कॉम्पोनेंट्स (स्ट्रिंग फील्डनाम, रीडर रीडर)। Http://lucene.apache.org/core/4_4_0/core/org/apache/lucene/analysis/Analyzer.html – Casper

4

आप कक्षा कक्षा का उपयोग कर सकते हैं PrefixQuery "शब्दकोश पर "सूचकांक। कक्षा लुसेने डिक्शनरी भी सहायक हो सकती है।

इस article पर एक नज़र डालें। यह बताता है कि "क्या आपका मतलब था" सुविधा को कार्यान्वित करना है? Google जैसे आधुनिक खोज इंजन में उपलब्ध है। आपको लेख में वर्णित कुछ जटिल की आवश्यकता नहीं हो सकती है। हालांकि लेख बताता है कि लुसीन वर्तनी पैकेज का उपयोग कैसे करें।

"डिक्शनरी" इंडेक्स बनाने का एक तरीका LuceneDictionary पर फिर से शुरू करना होगा।

आशा है कि यह मदद करता है

+1

यह एक पाठ्यपुस्तक उदाहरण है कि क्यों लिंक-केवल उत्तर अच्छे जवाब नहीं देते हैं, क्योंकि यह लिंक अब रोका गया है। –

24

यहाँ, Lucene.NET के लिए सी # में चटाई के कार्यान्वयन का लिप्यंतरण है एक पाठ बॉक्स तारों jQuery का स्वत: पूर्ण सुविधा का उपयोग कर के लिए एक टुकड़ा के साथ लगता है।

<input id="search-input" name="query" placeholder="Search database." type="text" /> 

... JQuery स्वत: पूर्ण:

// don't navigate away from the field when pressing tab on a selected item 
$("#search-input").keydown(function (event) { 
    if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { 
     event.preventDefault(); 
    } 
}); 

$("#search-input").autocomplete({ 
    source: '@Url.Action("SuggestTerms")', // <-- ASP.NET MVC Razor syntax 
    minLength: 2, 
    delay: 500, 
    focus: function() { 
     // prevent value inserted on focus 
     return false; 
    }, 
    select: function (event, ui) { 
     var terms = this.value.split(/\s+/); 
     terms.pop(); // remove dropdown item 
     terms.push(ui.item.value.trim()); // add completed item 
     this.value = terms.join(" "); 
     return false; 
    }, 
}); 

... यहाँ ASP.NET MVC नियंत्रक कोड है:

// 
    // GET: /MyApp/SuggestTerms?term=something 
    public JsonResult SuggestTerms(string term) 
    { 
     if (string.IsNullOrWhiteSpace(term)) 
      return Json(new string[] {}); 

     term = term.Split().Last(); 

     // Fetch suggestions 
     string[] suggestions = SearchSvc.SuggestTermsFor(term).ToArray(); 

     return Json(suggestions, JsonRequestBehavior.AllowGet); 
    } 

... और यहां सी # में चटाई के कोड है:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Lucene.Net.Store; 
using Lucene.Net.Index; 
using Lucene.Net.Search; 
using SpellChecker.Net.Search.Spell; 
using Lucene.Net.Analysis; 
using Lucene.Net.Analysis.Standard; 
using Lucene.Net.Analysis.NGram; 
using Lucene.Net.Documents; 

namespace Cipher.Services 
{ 
    /// <summary> 
    /// Search term auto-completer, works for single terms (so use on the last term of the query). 
    /// Returns more popular terms first. 
    /// <br/> 
    /// Author: Mat Mannion, [email protected] 
    /// <seealso cref="http://stackoverflow.com/questions/120180/how-to-do-query-auto-completion-suggestions-in-lucene"/> 
    /// </summary> 
    /// 
    public class SearchAutoComplete { 

     public int MaxResults { get; set; } 

     private class AutoCompleteAnalyzer : Analyzer 
     { 
      public override TokenStream TokenStream(string fieldName, System.IO.TextReader reader) 
      { 
       TokenStream result = new StandardTokenizer(kLuceneVersion, reader); 

       result = new StandardFilter(result); 
       result = new LowerCaseFilter(result); 
       result = new ASCIIFoldingFilter(result); 
       result = new StopFilter(false, result, StopFilter.MakeStopSet(kEnglishStopWords)); 
       result = new EdgeNGramTokenFilter(
        result, Lucene.Net.Analysis.NGram.EdgeNGramTokenFilter.DEFAULT_SIDE,1, 20); 

       return result; 
      } 
     } 

     private static readonly Lucene.Net.Util.Version kLuceneVersion = Lucene.Net.Util.Version.LUCENE_29; 

     private static readonly String kGrammedWordsField = "words"; 

     private static readonly String kSourceWordField = "sourceWord"; 

     private static readonly String kCountField = "count"; 

     private static readonly String[] kEnglishStopWords = { 
      "a", "an", "and", "are", "as", "at", "be", "but", "by", 
      "for", "i", "if", "in", "into", "is", 
      "no", "not", "of", "on", "or", "s", "such", 
      "t", "that", "the", "their", "then", "there", "these", 
      "they", "this", "to", "was", "will", "with" 
     }; 

     private readonly Directory m_directory; 

     private IndexReader m_reader; 

     private IndexSearcher m_searcher; 

     public SearchAutoComplete(string autoCompleteDir) : 
      this(FSDirectory.Open(new System.IO.DirectoryInfo(autoCompleteDir))) 
     { 
     } 

     public SearchAutoComplete(Directory autoCompleteDir, int maxResults = 8) 
     { 
      this.m_directory = autoCompleteDir; 
      MaxResults = maxResults; 

      ReplaceSearcher(); 
     } 

     /// <summary> 
     /// Find terms matching the given partial word that appear in the highest number of documents.</summary> 
     /// <param name="term">A word or part of a word</param> 
     /// <returns>A list of suggested completions</returns> 
     public IEnumerable<String> SuggestTermsFor(string term) 
     { 
      if (m_searcher == null) 
       return new string[] { }; 

      // get the top terms for query 
      Query query = new TermQuery(new Term(kGrammedWordsField, term.ToLower())); 
      Sort sort = new Sort(new SortField(kCountField, SortField.INT)); 

      TopDocs docs = m_searcher.Search(query, null, MaxResults, sort); 
      string[] suggestions = docs.ScoreDocs.Select(doc => 
       m_reader.Document(doc.Doc).Get(kSourceWordField)).ToArray(); 

      return suggestions; 
     } 


     /// <summary> 
     /// Open the index in the given directory and create a new index of word frequency for the 
     /// given index.</summary> 
     /// <param name="sourceDirectory">Directory containing the index to count words in.</param> 
     /// <param name="fieldToAutocomplete">The field in the index that should be analyzed.</param> 
     public void BuildAutoCompleteIndex(Directory sourceDirectory, String fieldToAutocomplete) 
     { 
      // build a dictionary (from the spell package) 
      using (IndexReader sourceReader = IndexReader.Open(sourceDirectory, true)) 
      { 
       LuceneDictionary dict = new LuceneDictionary(sourceReader, fieldToAutocomplete); 

       // code from 
       // org.apache.lucene.search.spell.SpellChecker.indexDictionary(
       // Dictionary) 
       //IndexWriter.Unlock(m_directory); 

       // use a custom analyzer so we can do EdgeNGramFiltering 
       var analyzer = new AutoCompleteAnalyzer(); 
       using (var writer = new IndexWriter(m_directory, analyzer, true, IndexWriter.MaxFieldLength.LIMITED)) 
       { 
        writer.MergeFactor = 300; 
        writer.SetMaxBufferedDocs(150); 

        // go through every word, storing the original word (incl. n-grams) 
        // and the number of times it occurs 
        foreach (string word in dict) 
        { 
         if (word.Length < 3) 
          continue; // too short we bail but "too long" is fine... 

         // ok index the word 
         // use the number of documents this word appears in 
         int freq = sourceReader.DocFreq(new Term(fieldToAutocomplete, word)); 
         var doc = MakeDocument(fieldToAutocomplete, word, freq); 

         writer.AddDocument(doc); 
        } 

        writer.Optimize(); 
       } 

      } 

      // re-open our reader 
      ReplaceSearcher(); 
     } 

     private static Document MakeDocument(String fieldToAutocomplete, string word, int frequency) 
     { 
      var doc = new Document(); 
      doc.Add(new Field(kSourceWordField, word, Field.Store.YES, 
        Field.Index.NOT_ANALYZED)); // orig term 
      doc.Add(new Field(kGrammedWordsField, word, Field.Store.YES, 
        Field.Index.ANALYZED)); // grammed 
      doc.Add(new Field(kCountField, 
        frequency.ToString(), Field.Store.NO, 
        Field.Index.NOT_ANALYZED)); // count 
      return doc; 
     } 

     private void ReplaceSearcher() 
     { 
      if (IndexReader.IndexExists(m_directory)) 
      { 
       if (m_reader == null) 
        m_reader = IndexReader.Open(m_directory, true); 
       else 
        m_reader.Reopen(); 

       m_searcher = new IndexSearcher(m_reader); 
      } 
      else 
      { 
       m_searcher = null; 
      } 
     } 


    } 
} 
+0

देखें कि आपके लिए एक सी # ड्राइवर स्निपेट जोड़ना संभव होगा जो आपके कोड को निष्पादित करता है, साथ ही साथ सूचकांक बनाने के लिए कोड? मैं आपके कोड को ठीक से संकलित करने के लिए प्राप्त कर सकता हूं, लेकिन मुझे यह पता लगाने में परेशानी है कि मेरी निर्देशिका कैसे बनाएं ताकि इसे ऊपर दिए गए कोड से पूछताछ की जा सके। – erik

+0

इससे कोई फर्क नहीं पड़ता कि निर्देशिका को पहले से अनुक्रमित कैसे किया गया है? क्या मैं इसे एक इंडेक्स पर चला सकता हूं जो स्नोबॉल विश्लेषक का उपयोग करके बनाया गया था? या क्या मुझे ऐसे क्षेत्र का उपयोग करना चाहिए जिसका विश्लेषण नहीं किया गया हो? (उपरोक्त एक ही प्रश्न पूछा) – NSjonas

+0

जावा सॉन्डर एन जेक्री या जावास्क्रिप्ट का उपयोग कर कोई उदाहरण ?? – Juhan

4

उपर्युक्त (बहुत सराहना) पी के अलावा ost re: C# रूपांतरण, क्या आप .NET 3.5 का उपयोग कर रहे हैं, आपको EdgeNGramTokenFilter के लिए कोड शामिल करना होगा - या कम से कम मैंने किया - ल्यूसीन 2.9.2 का उपयोग करके - यह फ़िल्टर .NET संस्करण से गायब है। बता सकता है। मुझे 2.9.3 में ऑनलाइन .NET 4 संस्करण और ऑनलाइन पोर्ट जाना था - उम्मीद है कि यह किसी के लिए प्रक्रिया को कम दर्दनाक बनाता है ...

संपादित करें: कृपया ध्यान दें कि सरणी SuggestTermsFor() फ़ंक्शन गिनती आरोही के अनुसार क्रमबद्ध है द्वारा दिया, तो आप शायद यह उल्टा करने के लिए अपनी सूची में पहले सबसे लोकप्रिय शब्द पाने के लिए चाहता हूँ

using System.IO; 
using System.Collections; 
using Lucene.Net.Analysis; 
using Lucene.Net.Analysis.Tokenattributes; 
using Lucene.Net.Util; 

namespace Lucene.Net.Analysis.NGram 
{ 

/** 
* Tokenizes the given token into n-grams of given size(s). 
* <p> 
* This {@link TokenFilter} create n-grams from the beginning edge or ending edge of a input token. 
* </p> 
*/ 
public class EdgeNGramTokenFilter : TokenFilter 
{ 
    public static Side DEFAULT_SIDE = Side.FRONT; 
    public static int DEFAULT_MAX_GRAM_SIZE = 1; 
    public static int DEFAULT_MIN_GRAM_SIZE = 1; 

    // Replace this with an enum when the Java 1.5 upgrade is made, the impl will be simplified 
    /** Specifies which side of the input the n-gram should be generated from */ 
    public class Side 
    { 
     private string label; 

     /** Get the n-gram from the front of the input */ 
     public static Side FRONT = new Side("front"); 

     /** Get the n-gram from the end of the input */ 
     public static Side BACK = new Side("back"); 

     // Private ctor 
     private Side(string label) { this.label = label; } 

     public string getLabel() { return label; } 

     // Get the appropriate Side from a string 
     public static Side getSide(string sideName) 
     { 
      if (FRONT.getLabel().Equals(sideName)) 
      { 
       return FRONT; 
      } 
      else if (BACK.getLabel().Equals(sideName)) 
      { 
       return BACK; 
      } 
      return null; 
     } 
    } 

    private int minGram; 
    private int maxGram; 
    private Side side; 
    private char[] curTermBuffer; 
    private int curTermLength; 
    private int curGramSize; 
    private int tokStart; 

    private TermAttribute termAtt; 
    private OffsetAttribute offsetAtt; 

    protected EdgeNGramTokenFilter(TokenStream input) : base(input) 
    { 
     this.termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute)); 
     this.offsetAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute)); 
    } 

    /** 
    * Creates EdgeNGramTokenFilter that can generate n-grams in the sizes of the given range 
    * 
    * @param input {@link TokenStream} holding the input to be tokenized 
    * @param side the {@link Side} from which to chop off an n-gram 
    * @param minGram the smallest n-gram to generate 
    * @param maxGram the largest n-gram to generate 
    */ 
    public EdgeNGramTokenFilter(TokenStream input, Side side, int minGram, int maxGram) 
     : base(input) 
    { 

     if (side == null) 
     { 
      throw new System.ArgumentException("sideLabel must be either front or back"); 
     } 

     if (minGram < 1) 
     { 
      throw new System.ArgumentException("minGram must be greater than zero"); 
     } 

     if (minGram > maxGram) 
     { 
      throw new System.ArgumentException("minGram must not be greater than maxGram"); 
     } 

     this.minGram = minGram; 
     this.maxGram = maxGram; 
     this.side = side; 
     this.termAtt = (TermAttribute)AddAttribute(typeof(TermAttribute)); 
     this.offsetAtt = (OffsetAttribute)AddAttribute(typeof(OffsetAttribute)); 
    } 

    /** 
    * Creates EdgeNGramTokenFilter that can generate n-grams in the sizes of the given range 
    * 
    * @param input {@link TokenStream} holding the input to be tokenized 
    * @param sideLabel the name of the {@link Side} from which to chop off an n-gram 
    * @param minGram the smallest n-gram to generate 
    * @param maxGram the largest n-gram to generate 
    */ 
    public EdgeNGramTokenFilter(TokenStream input, string sideLabel, int minGram, int maxGram) 
     : this(input, Side.getSide(sideLabel), minGram, maxGram) 
    { 

    } 

    public override bool IncrementToken() 
    { 
     while (true) 
     { 
      if (curTermBuffer == null) 
      { 
       if (!input.IncrementToken()) 
       { 
        return false; 
       } 
       else 
       { 
        curTermBuffer = (char[])termAtt.TermBuffer().Clone(); 
        curTermLength = termAtt.TermLength(); 
        curGramSize = minGram; 
        tokStart = offsetAtt.StartOffset(); 
       } 
      } 
      if (curGramSize <= maxGram) 
      { 
       if (!(curGramSize > curTermLength   // if the remaining input is too short, we can't generate any n-grams 
        || curGramSize > maxGram)) 
       {  // if we have hit the end of our n-gram size range, quit 
        // grab gramSize chars from front or back 
        int start = side == Side.FRONT ? 0 : curTermLength - curGramSize; 
        int end = start + curGramSize; 
        ClearAttributes(); 
        offsetAtt.SetOffset(tokStart + start, tokStart + end); 
        termAtt.SetTermBuffer(curTermBuffer, start, curGramSize); 
        curGramSize++; 
        return true; 
       } 
      } 
      curTermBuffer = null; 
     } 
    } 

    public override Token Next(Token reusableToken) 
    { 
     return base.Next(reusableToken); 
    } 
    public override Token Next() 
    { 
     return base.Next(); 
    } 
    public override void Reset() 
    { 
     base.Reset(); 
     curTermBuffer = null; 
    } 
} 
} 
+0

इससे कोई फर्क नहीं पड़ता कि निर्देशिका को पहले अनुक्रमित कैसे किया गया है? क्या मैं इसे एक इंडेक्स पर चला सकता हूं जो स्नोबॉल विश्लेषक का उपयोग करके बनाया गया था? या क्या मुझे ऐसे क्षेत्र का उपयोग करना चाहिए जिसका विश्लेषण नहीं किया गया हो? – NSjonas

4

ल्यूसीन 4.2 पर आधारित मेरा कोड,

import java.io.File; 
import java.io.IOException; 

import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; 
import org.apache.lucene.index.DirectoryReader; 
import org.apache.lucene.index.IndexWriterConfig; 
import org.apache.lucene.index.IndexWriterConfig.OpenMode; 
import org.apache.lucene.search.spell.Dictionary; 
import org.apache.lucene.search.spell.LuceneDictionary; 
import org.apache.lucene.search.spell.PlainTextDictionary; 
import org.apache.lucene.search.spell.SpellChecker; 
import org.apache.lucene.store.Directory; 
import org.apache.lucene.store.FSDirectory; 
import org.apache.lucene.store.IOContext; 
import org.apache.lucene.store.RAMDirectory; 
import org.apache.lucene.util.Version; 
import org.wltea4pinyin.analyzer.lucene.IKAnalyzer4PinYin; 


/** 
* 
* 
* @author <a href="mailto:[email protected]"></a> 
* @version 2013-11-25上午11:13:59 
*/ 
public class LuceneSpellCheckerDemoService { 

private static final String INDEX_FILE = "/Users/r/Documents/jar/luke/youtui/index"; 
private static final String INDEX_FILE_SPELL = "/Users/r/Documents/jar/luke/spell"; 

private static final String INDEX_FIELD = "app_name_quanpin"; 

public static void main(String args[]) { 

    try { 
     // 
     PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new IKAnalyzer4PinYin(
       true)); 

     // read index conf 
     IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_42, wrapper); 
     conf.setOpenMode(OpenMode.CREATE_OR_APPEND); 

     // read dictionary 
     Directory directory = FSDirectory.open(new File(INDEX_FILE)); 
     RAMDirectory ramDir = new RAMDirectory(directory, IOContext.READ); 
     DirectoryReader indexReader = DirectoryReader.open(ramDir); 

     Dictionary dic = new LuceneDictionary(indexReader, INDEX_FIELD); 


     SpellChecker sc = new SpellChecker(FSDirectory.open(new File(INDEX_FILE_SPELL))); 
     //sc.indexDictionary(new PlainTextDictionary(new File("myfile.txt")), conf, false); 
     sc.indexDictionary(dic, conf, true); 
     String[] strs = sc.suggestSimilar("zhsiwusdazhanjiangshi", 10); 
     for (int i = 0; i < strs.length; i++) { 
      System.out.println(strs[i]); 
     } 
     sc.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 


} 
+0

हाय, क्या आप मुझे बता सकते हैं कि index_file और Index_file_spell के बीच क्या अंतर है? – SoluableNonagon

+0

Index_file दस्तावेजों की अनुक्रमणिका है। और index_file_spell इंडेक्स_फाइल का उपयोग इंडेक्स प्राप्त करने के लिए जो स्वत: पूर्णता/सुझावों के लिए उपयोग करता है – user2098849

संबंधित मुद्दे