实现像百度一样的自动补全功能
???? ??}
?
???? ??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 {
???? ?Sugesstion autocomplete = new Sugesstion("/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]
???? }
?}
1 楼 hailongshih 2013-11-28 lz用哪个版本jar包,试过3.0.3 3.0.2都不行