lucene6.4.2高亮测试源码 一定要导入这个包lucene-memory-6.4.2.jar

来源:互联网 发布:java开发一个博客系统 编辑:程序博客网 时间:2024/06/18 01:24

一定要导入这个包lucene-memory-6.4.2.jar,虽然没有显示地调用。坑死我了。

测试结果:

Found 3 hits.
1. 193398817 Lucene in Action小说
高亮关键字  Lucene in Action<span style='color:red;'>小</span><span style='color:red;'>说</span>
2. 9900333X The Art of Computer Science
高亮关键字  The Art of <span style='color:red;'>Computer</span> Science
3. 55320055Z Lucene for Dummies说
高亮关键字  Lucene for Dummies<span style='color:red;'>说</span>


import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.TokenStream;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.StringField;import org.apache.lucene.document.TextField;import org.apache.lucene.index.DirectoryReader;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.queryparser.classic.ParseException;import org.apache.lucene.queryparser.classic.QueryParser;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopScoreDocCollector;import org.apache.lucene.search.highlight.Formatter;import org.apache.lucene.search.highlight.Highlighter;import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;import org.apache.lucene.search.highlight.QueryScorer;import org.apache.lucene.search.highlight.SimpleHTMLFormatter;import org.apache.lucene.store.Directory;import org.apache.lucene.store.RAMDirectory;import java.io.IOException;import java.io.StringReader; public class HeighterTest {//static StandardAnalyzer analyzer = new StandardAnalyzer();  public static void main(String[] args) throws IOException, ParseException {    // 0. Specify the analyzer for tokenizing text.    //    The same analyzer should be used for indexing and searching    Analyzer analyzer = new StandardAnalyzer();     // 1. create the index    Directory index = new RAMDirectory();//Directory index=FSDirectory.open(Paths.get("c:/demo"));//open("c:/demo");    IndexWriterConfig config = new IndexWriterConfig(analyzer);     IndexWriter w = new IndexWriter(index, config);    addDoc(w, "Lucene in Action小说", "193398817");    addDoc(w, "Lucene for Dummies说", "55320055Z");    addDoc(w, "Managing Gigabytes", "55063554A");    addDoc(w, "The Art of Computer Science", "9900333X");    w.close();     // 2. query    String querystr = args.length > 0 ? args[0] : "小说 ddd Computer";     // the "title" arg specifies the default field to use    // when no field is explicitly specified in the query.    Query q = new QueryParser("title", analyzer).parse(querystr);     // 3. search    int hitsPerPage = 8;    IndexReader reader = DirectoryReader.open(index);    IndexSearcher searcher = new IndexSearcher(reader);    TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage);    searcher.search(q, collector);    ScoreDoc[] hits = collector.topDocs().scoreDocs;         // 4. display results    QueryScorer scorer = new QueryScorer(q);    Formatter formatter = new SimpleHTMLFormatter("<span style='color:red;'>", "</span>");    Highlighter highlight = new Highlighter(formatter,scorer);   // Highlighter highlight = new Highlighter(scorer);      System.out.println("Found " + hits.length + " hits.");    for(int i=0;i<hits.length;++i) {      int docId = hits[i].doc;      Document d = searcher.doc(docId);      System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));                  // 高亮关键字        try {      TokenStream tokenStream = analyzer.tokenStream("title", new StringReader( d.get("title")));      String highlightStr = highlight.getBestFragment(tokenStream,  d.get("title"));   System.out.println("高亮关键字  "+highlightStr);   } catch (InvalidTokenOffsetsException e) {   // TODO Auto-generated catch block   e.printStackTrace();   }    }    // reader can only be closed when there    // is no need to access the documents any more.    reader.close();  }   private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {    Document doc = new Document();    doc.add(new TextField("title", title, Field.Store.YES));     // use a string field for isbn because we don't want it tokenized    doc.add(new StringField("isbn", isbn, Field.Store.YES));    w.addDocument(doc);  }  /**    * 高亮设置    *     * @param query    * @param doc    * @param field    * @return    */  //  protected static String toHighlighter(Query query, Document doc, String field) {  //      try {  //          SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<font color=\"blue\">", "</font>");  //          Highlighter highlighter = new Highlighter(simpleHtmlFormatter, new QueryScorer(query));  //          TokenStream tokenStream1 = analyzer.tokenStream("text", new StringReader(doc.get(field)));  //          String highlighterStr = highlighter.getBestFragment(tokenStream1, doc.get(field));  //          return highlighterStr == null ? doc.get(field) : highlighterStr;  //      } catch (IOException e) {  //          e.printStackTrace();  //      } catch (InvalidTokenOffsetsException e) {  //          e.printStackTrace();  //      }  //      return null;  //  }  }



之前一直报这个错,导入这个包lucene-memory-6.4.2.jar就好了,虽然没有显示地调用:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/lucene/index/memory/MemoryIndex
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.getLeafContext(WeightedSpanTermExtractor.java:399)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extractWeightedTerms(WeightedSpanTermExtractor.java:363)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extract(WeightedSpanTermExtractor.java:142)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extract(WeightedSpanTermExtractor.java:113)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.extract(WeightedSpanTermExtractor.java:113)
at org.apache.lucene.search.highlight.WeightedSpanTermExtractor.getWeightedSpanTerms(WeightedSpanTermExtractor.java:522)
at org.apache.lucene.search.highlight.QueryScorer.initExtractor(QueryScorer.java:218)
at org.apache.lucene.search.highlight.QueryScorer.init(QueryScorer.java:186)
at org.apache.lucene.search.highlight.Highlighter.getBestTextFragments(Highlighter.java:195)
at org.apache.lucene.search.highlight.Highlighter.getBestFragments(Highlighter.java:155)
at org.apache.lucene.search.highlight.Highlighter.getBestFragment(Highlighter.java:101)
at HeighterTest.main(HeighterTest.java:80)
Caused by: java.lang.ClassNotFoundException: org.apache.lucene.index.memory.MemoryIndex
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 12 more


0 0
原创粉丝点击