LuceneUtil使用反射,封装通用的方法

package loaderman.util;

import java.io.File;
import java.lang.reflect.Method;

import loaderman.entity.Article;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 工具类*/
public class LuceneUtil {

    private static Directory directory;
    private static Version version;
    private static Analyzer analyzer;
    private static MaxFieldLength maxFieldLength;

    static{
        try {
            directory =  FSDirectory.open(new File("D:/IndexDBDBDB"));
            version = Version.LUCENE_30;
            analyzer = new StandardAnalyzer(version);
            maxFieldLength = MaxFieldLength.LIMITED;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static Directory getDirectory() {
        return directory;
    }

    public static Version getVersion() {
        return version;
    }

    public static Analyzer getAnalyzer() {
        return analyzer;
    }

    public static MaxFieldLength getMaxFieldLength() {
        return maxFieldLength;
    }

    //不让外界new该帮助类
    private LuceneUtil(){}

    //将JavaBean转成Document对象
    public static Document javabean2document(Object obj) throws Exception{
        //创建Docuemnt对象
        Document document = new Document();
        //获取obj引用的对象字节码
        Class clazz = obj.getClass();
        //通过对象字节码获取私有的属性
        java.lang.reflect.Field[] reflectFields = clazz.getDeclaredFields();
        //迭代
        for(java.lang.reflect.Field reflectField : reflectFields){
            //强力反射
            reflectField.setAccessible(true);
            //获取属性名,id/title/content
            String name = reflectField.getName();
            //人工拼接方法名
            String methodName = "get" + name.substring(0,1).toUpperCase()+name.substring(1);
            //获取方法,例如:getId()/getTitle()/getContent()
            Method method = clazz.getMethod(methodName,null);
            //执行方法
            String value = method.invoke(obj,null).toString();
            //加入到Document对象中去,这时javabean的属性与document对象的属性相同
            document.add(new Field(name,value,Store.YES,Index.ANALYZED));
        }
        //返回document对象
        return document;
    }

    //将Document对象转成JavaBean对象
    public static Object document2javabean(Document document,Class clazz) throws Exception{
        Object obj = clazz.newInstance();
        java.lang.reflect.Field[] reflectFields = clazz.getDeclaredFields();
        for(java.lang.reflect.Field reflectField : reflectFields){
            reflectField.setAccessible(true);
            String name = reflectField.getName();//id/title/content
            String value = document.get(name);//1/培训/传智是一家培训机构
            BeanUtils.setProperty(obj,name,value);//封装javabean对应的属性中去,通过setXxx()方法
        }
        return obj;
    }
    //测试
    public static void main(String[] args) throws Exception{
        Article aritcle = new Article(1,"学习","学习使人快乐...");
        Document document = LuceneUtil.javabean2document(aritcle);

        System.out.println("---------------------------------------");

        Article article = (Article) LuceneUtil.document2javabean(document,Article.class);
        System.out.println(article);
    }

}

 


 

package loaderman.secondapp;

import java.util.ArrayList;
import java.util.List;

import loaderman.entity.Article;
import loaderman.util.LuceneUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.junit.Test;


/**
 * 重构

 */
public class SecondApp {

    /**
     * 创建索引库
     */
    @Test
    public void createIndexDB() throws Exception{
        Article article = new Article(1,"培训","传智是一家it培训机构");
        //Article article = new Article(2,"培训","北大是一家it培训机构");
        //Article article = new Article(3,"培训","中大是一家it培训机构");
        Document document = LuceneUtil.javabean2document(article);
        IndexWriter indexWriter = new IndexWriter(LuceneUtil.getDirectory(),LuceneUtil.getAnalyzer(),LuceneUtil.getMaxFieldLength());
        indexWriter.addDocument(document);
        indexWriter.close();
    }

    /**
     * 根据关键字从索引库中查询符合条件的数据
     */
    @Test
    public void findIndexDB() throws Exception{
        String keywords = "培训";
        List<Article> articleList = new ArrayList<Article>();
        QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(),"content",LuceneUtil.getAnalyzer());
        Query query = queryParser.parse(keywords);
        IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
        TopDocs topDocs = indexSearcher.search(query,100);
        for(int i=0;i<topDocs.scoreDocs.length;i++){
            ScoreDoc scoreDoc = topDocs.scoreDocs[i];
            int no = scoreDoc.doc;
            Document document = indexSearcher.doc(no);
            Article article = (Article)LuceneUtil.document2javabean(document,Article.class);
            articleList.add(article);
        }
        for(Article a : articleList){
            System.out.println( a );
        }
    }
}

 

posted on 2018-12-03 16:18  LoaderMan  阅读(578)  评论(0编辑  收藏  举报

导航