lucene学习笔记

版本:lucene5.5 
全文搜索基本由三部分组成: 
- 索引部分 
- 分词部分 
- 搜索部分

创建索引基本步骤: 
1.创建Directory

Directory directory  =new RAMDirectory();// 创建在内存的索引
            Directory directory =  FSDirectory.open(Paths.get("路径")); //创建在硬盘上
  • 1
  • 2

2.创建IndexWrider

IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer());  //分词器
IndexWriter idw = new IndexWriter(directory, iwc);
  • 1
  • 2

3.创建document对象,并添加域对象,再通过IndexWriter添加文档

//3.创建document对象
            Document doc = null;
            //4.为Document对象添加field
            File f= new File("F:\测试\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.getAbsolutePath(),Field.Store.YES,Field.Index.NOT_ANALYZED));//此处的Field是3.x版本
                //5.通过IndexWriter 添加文档
                idw.addDocument(doc);
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
 FieldType type = new FieldType();
    type.setIndexOptions(IndexOptions.DOCS);//域的索引选项
    type.setTokenized(false);//是否分词
    type.setStored(true);//是否存储
    doc.add(new Field("path",file.getAbsolutePath(),type)); //5.x版本
  • 1
  • 2
  • 3
  • 4
  • 5

搜索部分基本步骤

//1.创建Directory
            Directory directory =  FSDirectory.open(Paths.get("F:\测试\index")); //创建在硬盘上
            //2.创建IndexReader
            IndexReader reader = DirectoryReader.open(directory);
            //3.根据IndexReader 创建IndexSearch
            IndexSearcher searcher = new IndexSearcher(reader);
            //4.创建搜索的Query
            //创建parser来确定要搜索文件的内容,第一个参数表示搜索的域
            QueryParser parser = new QueryParser("content", new StandardAnalyzer());
            //创建Query 表示搜索域为content中包含  的文档
            Query query = parser.parse("black");
            //5.根据seacher搜索并且返回TopDocs
            TopDocs tds = searcher.search(query, 10);//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")+"]");
            }

            reader.close();
            //9.关闭reader



http://m.blog.csdn.net/linyuxxin/article/details/51298090
原文地址:https://www.cnblogs.com/tianciliangen/p/7844999.html