lucene4入门实例
lucene4和lucene3相比,有了较大的改动。
直接贴代码吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | public void ram()throws Exception{ //使用内存目录,索引保存的地方 Directory dir=new RAMDirectory(); //使用IK分词器 Analyzer analyzer=new IKAnalyzer(true); //注意该类初始化,需要添加版本号,以前lucene3不需要 //IndexWriterConfig iwc=new IndexWriterConfig(analyzer); lucene3初始化的方法 IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_42, analyzer); //索引保存在内存中 IndexWriter writer=new IndexWriter(dir, iwc); for(int i=0; i < ids.length; i++) { Document doc=new Document(); doc.add(new StringField("id", ids[i], Store.YES)); //doc.add(new Field("content", content[i], Store.YES,Index.ANALYZED)); lucene3添加方法 //lucene4使用方法 FieldType ft=new FieldType(); ft.setStored(true); ft.setTokenized(true); doc.add(new Field("content", content[i], ft)); doc.add(new StringField("city", city[i], Store.YES)); writer.addDocument(doc); } System.out.println("init ok?"); writer.close(); //开始查询 IndexReader reader=DirectoryReader.open(dir); IndexSearcher searcher=new IndexSearcher(reader); //Term term=new Term("content", "汉语词法或其它汉语语言知识进行分词"); //TermQuery 最小分词单位,一般会去查询id比较合适,汉子需要分词,就不适合了 //TermQuery query=new TermQuery(term); //使用QueryParser查询分析器构造Query对象 QueryParser qp = new QueryParser(Version.LUCENE_42, "content", new IKAnalyzer(true)); qp.setDefaultOperator(QueryParser.AND_OPERATOR); Query q = qp.parse("汉语词法或其它汉语语言知识进行分词"); System.out.println("Query = " + q); TopDocs topdocs=searcher.search(q, 5); ScoreDoc[] scoreDocs=topdocs.scoreDocs; System.out.println("查询结果总数---" + topdocs.totalHits+"最大的评分--"+topdocs.getMaxScore()); //打印查询结果 for(int i=0; i < scoreDocs.length; i++) { int doc = scoreDocs[i].doc; Document document = searcher.doc(doc); System.out.println("content===="+document.get("content")+" id:"+document.get("id")); System.out.println("id--" + scoreDocs[i].doc + "---scors--" + scoreDocs[i].score+"---index--"+scoreDocs[i].shardIndex); } reader.close(); } |
主函数为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Test{ protected String[] ids={"1", "1","3","4"}; protected String[] content={"Amsterdam has lost of add cancals", "i love add this girl", "我是中国人,爱中国", "第一类方法应用词典匹配、汉语词法或其它汉语语言知识进行分词,如:最大匹配法、最小分词方法等。这类方法简单、分词效率较高,但汉语语言现象复杂丰富,词典的完备性、规则的一致性等问题使其难以适应开放的大规模文本的分词处理。第二类基于统计的分词方法则基于字和词的统计信息,如把相邻字间的信息、词频及相应的共现信息等应用于分词,由于这些信息是通过调查真实语料而取得的,因而基于统计的分词方法具有较好的实用性。 "}; protected String[] city={"Amsterdam", "Venice","qq","tt"}; public static void main(String[] args){ Test test=new Test(); try{ test.ram(); }catch(Exception e){ e.printStackTrace(); } } } |
本文固定链接: http://www.chepoo.com/lucene4-easy-demo.html | IT技术精华网