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 block
e.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 block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.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 block
e.printStackTrace();
} catch (LockObtainFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(writer!=null)
{
try {
writer.close();
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//测试类
package org.se.lucene;
import org.junit.Test;
public class test {
@Test
public void testIndex()
{
lucene_index l_index=new lucene_index();
l_index.index();
}
@Test
public void testquary()
{
lucene_index l_index=new lucene_index();
l_index.quary();
}
}
Lucene小练二(还是索引)
最新推荐文章于 2012-09-20 12:00:55 发布