Lucene V3.0.2分詞、高亮

來源:互聯網
上載者:User

Lucene版本升級到3.0以後,原來的分詞方式(token=tokenStream.next())的方式已經被拋棄,轉而使用TermAttribute,本例使用SmartChineseAnalyzer示範如何分詞,此外,本例還示範了如何對命中文檔域進行高亮顯示。

 

package index;<br />import java.io.File;<br />import java.io.IOException;<br />import java.io.StringReader;<br />import org.apache.lucene.analysis.Analyzer;<br />import org.apache.lucene.analysis.TokenStream;<br />import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;<br />import org.apache.lucene.analysis.tokenattributes.TermAttribute;<br />import org.apache.lucene.document.Document;<br />import org.apache.lucene.document.Field;<br />import org.apache.lucene.document.Field.Index;<br />import org.apache.lucene.document.Field.Store;<br />import org.apache.lucene.index.CorruptIndexException;<br />import org.apache.lucene.index.IndexWriter;<br />import org.apache.lucene.index.IndexWriter.MaxFieldLength;<br />import org.apache.lucene.queryParser.ParseException;<br />import org.apache.lucene.queryParser.QueryParser;<br />import org.apache.lucene.search.IndexSearcher;<br />import org.apache.lucene.search.Query;<br />import org.apache.lucene.search.ScoreDoc;<br />import org.apache.lucene.search.TopDocs;<br />import org.apache.lucene.search.highlight.Highlighter;<br />import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;<br />import org.apache.lucene.search.highlight.QueryScorer;<br />import org.apache.lucene.search.highlight.SimpleFragmenter;<br />import org.apache.lucene.search.highlight.SimpleHTMLFormatter;<br />import org.apache.lucene.store.FSDirectory;<br />import org.apache.lucene.store.LockObtainFailedException;<br />import org.apache.lucene.util.Version;<br />public class AnalzyerTest {<br />/**<br /> * lucene3.0開始已經拋棄了原來的分詞方式,轉而使用新的分詞方式<br><br /> * 本方法以SmartChineseAnalyzer為例,示範如何分詞以及取得分詞之後的term<br /> *<br /> * @throws Exception<br /> */<br />public static void analysis() throws Exception {<br />Analyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_30);<br />String string = "中國人民銀行採取了一系列措施防止人民幣升值,但是很遺憾,這些措施在今天看來其作用是微乎其微的。難道真的就沒有什麼別的措施防止人民幣再次瘋狂升值了嗎?";<br />StringReader reader = new StringReader(string);<br />TokenStream ts = analyzer.tokenStream("", reader);<br />TermAttribute termAttribute = ts.getAttribute(TermAttribute.class);<br />while (ts.incrementToken()) {<br />System.out.print(termAttribute.term() + " ");<br />}<br />System.out.println();<br />}<br />/**<br /> * 建索引<br><br /> * 在構造IndexWriter時必須使用Directory作為參數了<br /> *<br /> * @throws CorruptIndexException<br /> * @throws LockObtainFailedException<br /> * @throws IOException<br /> */<br />private static void build() throws CorruptIndexException, LockObtainFailedException, IOException {<br />String path = "index";<br />IndexWriter writer = new IndexWriter(FSDirectory.open(new File(path)), new SmartChineseAnalyzer(Version.LUCENE_30), true, MaxFieldLength.LIMITED);<br />Document document = new Document();<br />document.add(new Field("text", "中國人民銀行採取了一系列措施防止人民幣升值,但是很遺憾,這些措施在今天看來其作用是微乎其微的。難道真的就沒有什麼別的措施防止人民幣再次瘋狂升值了嗎?", Store.YES, Index.ANALYZED));<br />writer.addDocument(document);<br />writer.optimize();<br />writer.close();<br />}<br />/**<br /> * 搜尋也沒有返回Hits類型結果的方法了<br /> *<br /> * @param keyword<br /> * @throws CorruptIndexException<br /> * @throws IOException<br /> * @throws ParseException<br /> * @throws InvalidTokenOffsetsException<br /> */<br />private static void search(String keyword) throws CorruptIndexException, IOException, ParseException, InvalidTokenOffsetsException {<br />Analyzer analyzer = new SmartChineseAnalyzer(Version.LUCENE_30);<br />QueryParser parser = new QueryParser(Version.LUCENE_30, "text", analyzer);<br />IndexSearcher searcher = new IndexSearcher(FSDirectory.open(new File("index")));<br />Query query = parser.parse(keyword);<br />System.out.println(query);<br />TopDocs topDocs = searcher.search(query, 10);<br />ScoreDoc[] scoreDocs = topDocs.scoreDocs;<br />System.out.println("hits:" + topDocs.totalHits);<br />for (ScoreDoc scoreDoc : scoreDocs) {<br />Document doc = searcher.doc(scoreDoc.doc);<br />String text = doc.get("text");<br />System.out.println(highlight(text, query, analyzer));<br />}<br />}<br />/**<br /> * 高亮關鍵詞<br /> *<br /> * @param content<br /> * 需要高亮的內容<br /> * @param query<br /> * 搜尋時使用的Query對象<br /> * @param analyzer<br /> * 分詞器<br /> * @return 高亮之後的文本<br /> * @throws IOException<br /> * @throws InvalidTokenOffsetsException<br /> */<br />private static String highlight(String content, Query query, Analyzer analyzer) throws IOException, InvalidTokenOffsetsException {<br />SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<b>", "</b>");<br />Highlighter highlighter = new Highlighter(formatter, new QueryScorer(query));<br />highlighter.setTextFragmenter(new SimpleFragmenter(25));<br />String resultString = highlighter.getBestFragment(analyzer.tokenStream("", new StringReader(content)), content);<br />return resultString + "...";<br />}<br />public static void main(String[] args) throws Exception {<br />analysis();<br />build();<br />search("中國 人民幣 升值");<br />}<br />}<br /> 

本例需要使用四個jar包:

lucene-core-3.0.3.jar 

lucene-highlighter-3.0.2.jar

lucene-smartcn-3.0.2.jar

lucene-memory-3.0.2.jar

 

在高亮時有一個特別需要注意的問題:

當輸入的查詢詞為"人民幣升值"時,會拋出NoClassDefFoundError:org/apache/lucene/index/memory/MemoryIndex異常,如果將“人民幣”與“升值”使用空格分開,則不會出現此異常。

解決方式是將lucene-memory-3.0.2.jar添加到classpath中。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.