lucene使用入门

1、使用环境需要jar包
     本人使用的是  
                 lucene8.X 
                需要jdk 1.9以上   
                io包  2.X以上
     需要软件可以找我要QQ我发给你 2607143474
2、入门步骤
(1)创建索引文件
 //1、创建一个Directory对象,指定索引保存的位置(RAMDirectory指定为内存)FSDirectory则指定为硬盘
    Directory dictionary = FSDirectory.open(new File("D:\\aa\\bb").toPath());
    //2、基于Directory对象创建一个IndexWriter对象
    IndexWriter indexWriter = new IndexWriter(dictionary, new IndexWriterConfig());
    //3、读取磁盘文件,每个文件创建一个文档对象
    File file = new File("D:\\aa\\cc");
    File[] files = file.listFiles();
    for (File f :
            files) {
        //读取文件名
        String filename = f.getName();
        //读取文件路径
        String pathname = f.getPath();
        //读取文件内容
        String s = FileUtils.readFileToString(f, "utf-8");
        //读取文件大小

        long l = FileUtils.sizeOf(f);
        //创建Field对象(创建域),把文件添加到域(字段)
        //参数1:域的名称   参数2:域的内容    参数3:是否存储
        Field fieldname = new TextField("name", filename, Field.Store.YES);
        Field fieldpath = new TextField("path", pathname, Field.Store.YES);
        Field fields = new TextField("context", s, Field.Store.YES);
        Field fieldl = new TextField("size", l + "", Field.Store.YES);
        //创建文档对象
        Document document = new Document();
        //向文档中添加域
        document.add(fieldname);
        document.add(fieldpath);
        document.add(fields);
        document.add(fieldl);
        //把文档对象写到索引库
        indexWriter.addDocument(document);

    }
    indexWriter.close();
(2)读取文件
     //1、创建一个Directory对象,指定索引保存的位置(RAMDirectory指定为内存)FSDirectory则指定为硬盘,内存会清空这不是我们需要的
    Directory dictionary = FSDirectory.open(new File("D:\\aa\\bb").toPath());
    //2、基于Directory对象创建一个IndexReader对象
    IndexReader indexReader = DirectoryReader.open(dictionary);
    //3、创建一个IndexSearcher对象,构造方法中的参数indexReader
    IndexSearcher indexSearcher = new IndexSearcher(indexReader);
    //4、创建一个Query对象,TermQuery
    Query query = new TermQuery(new Term("context", "aaa"));
    //5、执行查询,得到一个TopDosc对象  参数1:查询对象   参数2:查询的最大记录数
    TopDocs search = indexSearcher.search(query, 10);
    System.out.println("查询总记录数" + search.totalHits);
    System.out.println("查询总记录数" + search.totalHits);
    //6.取文档列表
    ScoreDoc[] scoreDocs = search.scoreDocs;
    //7、打印文档内容
    for (ScoreDoc c :
            scoreDocs) {
        int doc = c.doc;
        Document doc1 = indexSearcher.doc(doc);
        System.out.println(doc1.get("size"));
        System.out.println(doc1.get("name"));
        System.out.println(doc1.get("path"));
        System.out.println(doc1.get("context"));
        System.out.println("----------------------------------------------------------------");

    }
    indexReader.close();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值