Lucene小练二(还是索引)

来源:互联网 发布:张海山锐线体简 mac版 编辑:程序博客网 时间:2024/06/06 01:57
package org.se.lucene;//创建索引import java.io.File;import java.io.IOException;import org.apache.lucene.analysis.standard.StandardAnalyzer;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.IndexWriterConfig;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.store.LockObtainFailedException;import org.apache.lucene.util.Version;public class lucene_index {private String[] ids={"1","2","3","4","5","6"};private String[] emails={"aa@aa.org","cc@cc.org","dd@@dd.org","bb@bb.org","ee@ee.org","ff@ff.org"};private String[] contents={"welcometotyu","hellowboy","higirl","howareyou","googluck","badgosh"};private int[] attachs={1,2,3,4,5,6};private String[] names={"liwu","zhangsan","xiaoqinag","laona","dabao","lisi"};private Directory directory=null;public lucene_index(){try {directory=FSDirectory.open(new File("f:/lucene/index02"));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void quary(){try {IndexReader reader=IndexReader.open(directory);System.out.println("numdocs"+reader.numDocs());System.out.println("maxDocs"+reader.maxDoc());} catch (CorruptIndexException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void index(){   IndexWriter writer=null;   Document doc=null;   try {writer =new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_36,    new StandardAnalyzer(Version.LUCENE_36)));for(int i=0;i<ids.length;i++){doc=new Document();    doc.add(new Field("id",ids[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));    doc.add(new Field("emails",emails[i],Field.Store.YES,Field.Index.NOT_ANALYZED));    doc.add(new Field("contents",contents[i],Field.Store.YES,Field.Index.ANALYZED));    doc.add(new Field("name",names[i],Field.Store.YES,Field.Index.NOT_ANALYZED_NO_NORMS));    writer.addDocument(doc); }} catch (CorruptIndexException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (LockObtainFailedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}   finally{   if(writer!=null)   {  try {writer.close();} catch (CorruptIndexException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}      }   }}}//测试类package org.se.lucene;import org.junit.Test;public class test {@Testpublic void testIndex(){lucene_index l_index=new lucene_index();l_index.index();    }@Testpublic void testquary(){lucene_index l_index=new lucene_index();l_index.quary();}}


原创粉丝点击