【索引建立步骤】
【创建Directory】
【创建writer】
【创建文档并添加索引】
文档和域的概念很重要
文档相当于表中的每一条记录,域相当于表中的每一个字段。
【查询索引的基本信息】
使用IndexReader进行查询。
【实践】
附:
IndexUtil.java:
1 package cn.hk.index; 2 3 import java.io.File; 4 import java.io.IOException; 5 6 import org.apache.lucene.analysis.standard.StandardAnalyzer; 7 import org.apache.lucene.document.Document; 8 import org.apache.lucene.document.Field; 9 import org.apache.lucene.index.CorruptIndexException;10 import org.apache.lucene.index.IndexReader;11 import org.apache.lucene.index.IndexWriter;12 import org.apache.lucene.index.IndexWriterConfig;13 import org.apache.lucene.store.Directory;14 import org.apache.lucene.store.FSDirectory;15 import org.apache.lucene.store.LockObtainFailedException;16 import org.apache.lucene.util.Version;17 18 public class IndexUtil {19 private String[] ids = {"1","2","3","4","5","6"};20 private String[] emails = {"aa@hk.arg","bb@hk.org","cc@hk.arg",21 "dd@hk.org","ee@hk.org","ff@hk.org"};22 private String[] content = {23 "welcome to visited the space","hello boy","my name is aa","i like football",24 "I like football and I like Basketball too","I like movie and swim"25 };26 private int[] attachs = {2,3,1,4,5,5};27 private String[] names = {"zhangsan","lisi","john","mike","jetty","jake"};28 29 private Directory directory = null;30 31 public IndexUtil(){32 try {33 directory = FSDirectory.open(new File("d://lucene/index02"));34 } catch (IOException e) {35 e.printStackTrace();36 }37 }38 39 public void query(){40 try {41 IndexReader reader = IndexReader.open(directory);42 //通过reader可以获取文档的数量43 System.out.println("numDocs:" + reader.numDocs());44 System.out.println("maxDocs" + reader.maxDoc());45 } catch (CorruptIndexException e) {46 47 e.printStackTrace();48 } catch (IOException e) {49 50 e.printStackTrace();51 }52 }53 54 55 public void index(){56 IndexWriter writer = null;57 try {58 writer = new IndexWriter(directory,new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35)));59 Document doc = null;60 for(int i=0;i
TestIndex.java:
1 package cn.hk.test; 2 3 import org.junit.Test; 4 5 import cn.hk.index.IndexUtil; 6 7 public class TestIndex { 8 9 @Test10 public void testIndex(){11 IndexUtil iu = new IndexUtil();12 iu.index();13 }14 15 @Test16 public void testQuery(){17 IndexUtil iu = new IndexUtil();18 iu.query();19 }20 }
index()运行结果:
query()运行结果