随笔-10  评论-66  文章-1  trackbacks-0
  最近开始搞下lucene,用空闲时间深入学习lucene的使用,希望今后能有所收获,呵呵。。.现在写的这个例子,是参考官方文档写的,写这些东西只是为了自己所走过的路,同时也非常希望得到各位兄弟的指点,让小弟少走点弯路

package test;

import java.io.IOException;

import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.junit.Before;
import org.junit.Test;

/**
 * @author dragon
 *
 */
public class TestBase {
   
    private String path;

    @Before
    public void init(){
        path = "/home/dragon/application/mywork/lucenetest/index";
    }
   
 
//    @Test     // 创建索引文件
    public void writerContent() throws CorruptIndexException, LockObtainFailedException, IOException{
         // IndexWriter的第三个参数为false时,则在已有的索引文件追加内容
        IndexWriter writer = new IndexWriter(path, new SimpleAnalyzer(), true);
       
       
        Document doc = new Document();
        String text = "Figure out which ClassLoader to use.  For JDK 1.2 and later use the";
        doc.add(new Field("content", text, Field.Store.YES, Field.Index.TOKENIZED));
       
        Document doc2 = new Document();
        String text2 = "context ClassLoader if possible.  Note: we defer linking the class";
        doc.add(new Field("content", text2, Field.Store.YES, Field.Index.TOKENIZED));
       
        Document doc3 = new Document();
        String text3 = "that calls an API only in JDK 1.2 until runtime so that we can catch";
        doc.add(new Field("content", text3, Field.Store.YES, Field.Index.TOKENIZED));
       
        writer.addDocument(doc);
        writer.addDocument(doc2);
        writer.addDocument(doc3);
         
        writer.optimize();
        writer.close();
       
    }
   
    @Test   // 搜索包含关键字key的内容
    public void searchContent() throws IOException, ParseException{
        Directory directory = FSDirectory.getDirectory(path);
        IndexSearcher search = new IndexSearcher(directory);
       
        String key = "use";
        QueryParser parser = new QueryParser("content",new SimpleAnalyzer());
        Query query = parser.parse(key);
       
        Hits hits = search.search(query);
       
        for(int i = 0; i < hits.length(); i++){
            Document doc = hits.doc(i);
            System.out.println(" 查询结果 : "+ doc.get("content"));
        }
       
        search.close();
        directory.close();
       
    }
   
}

posted on 2008-01-21 21:02 javadragon 阅读(857) 评论(0)  编辑  收藏 所属分类: lucene

只有注册用户登录后才能发表评论。


网站导航: