首页 > 代码库 > Lucene的学习与总结(二)

Lucene的学习与总结(二)

一、Lucene的基础(2017-05-11 10:40:46)

1、Lucene的下载

API的下载:http://pan.baidu.com/s/1nvLTG0L

2、Lucene的使用

/**
     * 建立索引
     */
    public void index(){
        IndexWriter writer = null;
        try {
            //1、创建Directory
            //Directory directory = new RAMDirectory();//建立在内存中
            //建立在硬盘上
            Directory directory = FSDirectory.open(new File("d:/import/studytool/Lucene/index01"));
            //2、创建IndexWriter
            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
            writer = new IndexWriter(directory, iwc);
            //3、创建Document对象
            Document doc = null;
            //4、为Document添加Field
            File f = new File("d:/import/studytool/Lucene/example");
            for(File file : f.listFiles()){
                doc = new Document();
                doc.add(new Field("content", new FileReader(file)));
                doc.add(new Field("filename", file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));
                doc.add(new Field("path",file.getPath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
                //5、通过IndexWriter添加文档到索引中
                writer.addDocument(doc);
            }
            
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (LockObtainFailedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

 

/**
     * 搜索
     */
    public void searcher(){
        try {
            //1、创建Directory
            Directory directory = FSDirectory.open(new File("d:/import/studytool/Lucene/index01"));
            //2、创建IndexReader
            IndexReader reader = IndexReader.open(directory);
            //3、根据IndexReader创建IndexSearcher
            IndexSearcher searcher = new IndexSearcher(reader);
            //4、创建搜索的Query
            //创建parser来确定要搜索文件的内容,第二个参数表示搜索的域
            QueryParser parser = new QueryParser(Version.LUCENE_35, "content", new StandardAnalyzer(Version.LUCENE_35));
            //创建query,表示搜索域为content中包含come的文档
            Query query = parser.parse("come");
            //5、根据Seacher搜索并返回TopDocs
            TopDocs tds = searcher.search(query, 10);
            //6、根据TopDocs获取ScoreDoc对象
            ScoreDoc[] sds = tds.scoreDocs;
            for(ScoreDoc sd : sds){
                //7、根据seacher和ScordDoc对象获取具体的Document对象
                Document d = searcher.doc(sd.doc);
                //8、根据Document对象获取需要的值
                System.out.println(d.get("filename")+"["+d.get("path")+"]");
            }
            //9、关闭reader
            reader.close();
        } catch (CorruptIndexException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

 

3、基本实例

4、系统架构

Lucene的学习与总结(二)