1、导入jar包

lucene-analyzers-common-7.6.0.jar

lucene-analyzers-smartcn-7.6.0.jar

lucene-core-7.6.0.jar

2、代码

package org.longIt.Lucene_app;

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.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import java.nio.file.Paths;

public class LuceneIndex {

    public static void main(String[] args) {
        addIndex();
        //searchIndex();
        //deleteIndex();
        //updateIndex();
    }

    private static void updateIndex() {
        // TODO Auto-generated method stub
        try {
            //指定索引库的目录
            Directory directory = FSDirectory.open(Paths.get("D:\\study\\lucene\\lucene_index\\article_tb"));

            //创建分词器  暂时使用  单字分词器  后期再改善
            Analyzer analyzer = new StandardAnalyzer();
            //创建IndexWriterConfig实例,通过IndexWriterConfig实例来指定创建索引的相关信息,比如指定分词器
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            //指定索引的创建方式
            config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

            //创建索引  更新索引   删除索引都是IndexWriter来实现
            IndexWriter  indexWriter = new IndexWriter(directory,config);

            //一个Document实例代表一条记录
            Document document = new Document();
            /**
             * StringField不会对关键字进行分词
             * Store.YES:会对数据进行存储并分词,如果为NO则不会对数据进行存储,索引还是会创建
             *
             * */
            document.add(new StringField("articleId", "0001", Field.Store.YES));
            document.add(new TextField("title", "幽幽而来", Field.Store.YES));
            document.add(new TextField("content", "这世间,必有一种懂得是精神,穿越灵魂", Field.Store.YES));

            /**
             * 通过indexWriter将数据写入至索引库
             * 更新的原理是先删除之前的索引,再创建新的索引,相当于更新是  删除与添加两个动作的合集
             * **/
            indexWriter.updateDocument(new Term("articleId","0001"), document);
            //提交事务
            indexWriter.commit();
            //关闭流资源
            indexWriter.close();
            System.out.println("=======索引更新成功======");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public static void addIndex() {
        try {
            Directory directory = FSDirectory.open(Paths.get("D:\\study\\lucene\\lucene_index\\article_tb"));
//创建IndexWriterConfig实例,通过IndexWriterConfig实例来指定创建索引的相关信息,比如指定分词器
            //创建分词器  暂时使用  单字分词器  后期再改善
            Analyzer analyzer = new StandardAnalyzer();

            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            //指定索引的创建方式
            config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

            //创建索引  更新索引   删除索引都是IndexWriter来实现
            IndexWriter indexWriter = new IndexWriter(directory, config);

            //一个Document实例代表一条记录
            Document document = new Document();
            /**
             * StringField不会对关键字进行分词
             * Store.YES:会对数据进行存储并分词,如果为NO则不会对数据进行存储,索引还是会创建
             *
             * */
            document.add(new StringField("articleId", "0001", Field.Store.YES));
            document.add(new TextField("title", "懂得人生0001", Field.Store.YES));
            document.add(new TextField("content", "一生一世", Field.Store.YES));

            //通过indexWriter将数据写入至索引库
            indexWriter.addDocument(document);
            //提交事务
            indexWriter.commit();
            //关闭流资源
            indexWriter.close();
            System.out.println("=======索引创建成功======");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void searchIndex() {

        try {
            Directory directory = FSDirectory.open(Paths.get("D:\\study\\lucene\\lucene_index\\article_tb"));

            //DirectoryReader的open方法指定需要读取的索引库信息,并返回相应的实例
            IndexReader indexReader = DirectoryReader.open(directory);

            //创建IndexSearcher实例,通过IndexSearcher实例进行全文检索
            IndexSearcher  indexSearcher = new IndexSearcher(indexReader);

            /*
            通过indexSearcher进行检索并指定两个参数
                第一个参数:封装查询的相关信息,比如说查询的关键字,是否需要分词或者需要分词的话采取什么分词器
               第二个参数:最多只要多少条记录
             TermQuery:中指定了查询的关键字以及查询哪一个字段
             TermQuery不会对关键字进行分词
            */
            Query query = new TermQuery(new Term("title","幽"));
            //查询索引表,最终数据都被封装在 TopDocs的实例中
            TopDocs topDocs = indexSearcher.search(query,10);

            //通过topDocs获取匹配全部记录
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            System.out.println("获取到的记录数:"+scoreDocs.length);

            for (int i = 0; i < scoreDocs.length; i++) {
                //获取记录的id
                int id = scoreDocs[i].doc;
                //文章的得分
                float score = scoreDocs[i].score;
                System.out.println("id:"+id+" 分章的得分:"+score);
                //查询数据表
                Document document = indexSearcher.doc(id);
                String articleId = document.get("articleId");
                String title = document.get("title");
                String content = document.get("content");
                System.out.println("articleId:"+articleId+" title:"+title+" content:"+content);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void deleteIndex() {
        // TODO Auto-generated method stub
        try {
            //指定索引库的目录
            Directory directory = FSDirectory.open(Paths.get("D:\\study\\lucene\\lucene_index\\article_tb"));

            //创建分词器  暂时使用  单字分词器  后期再改善
            Analyzer analyzer = new StandardAnalyzer();
            //创建IndexWriterConfig实例,通过IndexWriterConfig实例来指定创建索引的相关信息,比如指定分词器
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            //指定索引的创建方式
            config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);

            //创建索引  更新索引   删除索引都是IndexWriter来实现
            IndexWriter  indexWriter = new IndexWriter(directory,config);

            //删除指定的索引
            indexWriter.deleteDocuments(new Term("articleId","0001"));

            //删除索引库中全部的索引
            //indexWriter.deleteAll();
            //提交事务
            indexWriter.commit();
            //关闭流资源
            indexWriter.close();
            System.out.println("=======索引删除成功======");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

}

Lucene入门实例-CRUD的更多相关文章

  1. Lucene建立索引搜索入门实例

                                第一部分:Lucene建立索引 Lucene建立索引主要有以下两步:第一步:建立索引器第二步:添加索引文件准备在f盘建立lucene文件夹,然后 ...

  2. springboot + mybatisPlus 入门实例 入门demo

    springboot + mybatisPlus 入门实例 入门demo 使用mybatisPlus的优势 集成mybatisplus后,简单的CRUD就不用写了,如果没有特别的sql,就可以不用ma ...

  3. React 入门实例教程(转载)

    本人转载自: React 入门实例教程

  4. struts入门实例

    入门实例 1  .下载struts-2.3.16.3-all  .不摆了.看哈就会下载了. 2  . 解压  后 找到 apps 文件夹. 3.    打开后将 struts2-blank.war   ...

  5. Vue.js2.0从入门到放弃---入门实例

    最近,vue.js越来越火.在这样的大浪潮下,我也开始进入vue的学习行列中,在网上也搜了很多教程,按着教程来做,也总会出现这样那样的问题(坑啊,由于网上那些教程都是Vue.js 1.x版本的,现在用 ...

  6. wxPython中文教程入门实例

    这篇文章主要为大家分享下python编程中有关wxPython的中文教程,分享一些wxPython入门实例,有需要的朋友参考下     wxPython中文教程入门实例 wx.Window 是一个基类 ...

  7. Omnet++ 4.0 入门实例教程

    http://blog.sina.com.cn/s/blog_8a2bb17d01018npf.html 在网上找到的一个讲解omnet++的实例, 是4.0下面实现的. 我在4.2上试了试,可以用. ...

  8. Spring中IoC的入门实例

    Spring中IoC的入门实例 Spring的模块化是很强的,各个功能模块都是独立的,我们可以选择的使用.这一章先从Spring的IoC开始.所谓IoC就是一个用XML来定义生成对象的模式,我们看看如 ...

  9. Node.js入门实例程序

    在使用Node.js创建实际“Hello, World!”应用程序之前,让我们看看Node.js的应用程序的部分.Node.js应用程序由以下三个重要组成部分: 导入需要模块: 我们使用require ...

随机推荐

  1. 爬虫----beautifulsoup的简单使用

    beautifulSoup使用: 简单来说,Beautiful Soup是python的一个库,最主要的功能是从网页抓取数据. pip3 install beautifulsoup4 解析器 Beau ...

  2. php url函数

    1.base64_encode 与 base64_decode base64_encode(string) 表示使用 MIME base64 对数据进行编码 base64_decode(string) ...

  3. git无法pull仓库refusing to merge unrelated histories (拒绝合并不相关仓库)

    原文地址 https://blog.csdn.net/lindexi_gd/article/details/52554159 本文讲的是把git在最新2.9.2,合并pull两个不同的项目,出现的问题 ...

  4. C++ GetUserName()

    关于函数“GetUserName()”,参见:https://msdn.microsoft.com/en-us/library/windows/desktop/ms724432(v=vs.85).as ...

  5. vue用webpack打包时引入es2015插件

    1.安装依赖包 $ npm install --save-div babel-preset-es2015 ps:babel-loader.babel-core应该是默认装好的,如果没有安装,请重新安装 ...

  6. 51 NOd 1459 迷宫游戏 (最短路径)

    1459 迷宫游戏  基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题  收藏  关注 你来到一个迷宫前.该迷宫由若干个房间组成,每个房间都有一个得分,第一次进入这个房间, ...

  7. ionic 3 build后图片无法显示

    运行命令 ionic cordova build android 生成了android-debug.apk. /home/han/project/zero_app/platforms/android/ ...

  8. __attribute__ ((default)) 和 __attribute__ ((hidden))

    制作一个共享库 /* a.h */ int func(); /* a.c */ #include <stdio.h> #include "a.h" int func() ...

  9. tjoi2018

    1.[TJOI2018]数学计算 傻逼题 会发现符合线段树分治的特点 每个数的操作范围都是连续的 然后就等于区间修改了 #include <bits/stdc++.h> using nam ...

  10. ELK安装(ubuntu)

    一.安装jdk8 经过我测试logstash5.x不支持java10和11,所以安装java8 加入LinuxUprising Java PPA sudo add-apt-repository ppa ...