Lucene入门实例-CRUD

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();
        }
    }

}

原文地址:https://www.cnblogs.com/xiaofengfree/p/10353679.html

时间: 2024-08-29 15:00:42

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

Lucene入门程序-Java API的简单使用

Lucene入门程序 准备环境 JDK: 1.8.0_162 IDE: Eclipse Neon.3 数据库: MySQL 5.7.20 Lucene: 4.10.4(已经很稳定了,高版本对部分分词器支持不好) 准备数据 SET FOREIGN_KEY_CHECKS=0; -------------------------------- Table structure for `book` -------------------------------- DROP TABLE IF EXISTS

DWR之入门实例(一)

DWR(Direct Web Remoting)是一个WEB远程调用框架.利用这个框架可以让AJAX开发变得很简单.利用DWR可以在客户端利用JavaScript直接调用服务端的Java方法并返回值给JavaScript就好像直接本地客户端调用一样(DWR根据Java类来动态生成JavaScrip代码).它的最新版本DWR0.6添加许多特性如:支持Dom Trees的自动配置,支持Spring(JavaScript远程调用spring bean),更好浏览器支持,还支持一个可选的commons-

React 入门实例教程

React 入门实例教程 作者: 阮一峰 日期: 2015年3月31日 现在最热门的前端框架,毫无疑问是 React . 上周,基于 React 的 React Native 发布,结果一天之内,就获得了 5000 颗星,受瞩目程度可见一斑. React 起源于 Facebook 的内部项目,因为该公司对市场上所有 JavaScript MVC 框架,都不满意,就决定自己写一套,用来架设 Instagram 的网站.做出来以后,发现这套东西很好用,就在2013年5月开源了. 由于 React 的

Java AIO 入门实例(转)

Java7 AIO入门实例,首先是服务端实现: 服务端代码 SimpleServer: Java代码   public class SimpleServer { public SimpleServer(int port) throws IOException { final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(por

FPGA入门实例一:LFSR

一:任务: 要求使用Verilog语言在Xilinx Virtex-6开发板上实现线性反馈移位寄存器(LFSR)的硬件逻辑设计. 二:前期准备: 基本上完成一个简单的设计需要用到以下几个软件 逻辑:Uedit32(硬件狗吐血推荐) 综合:ISE14.1 仿真:Modelsim SE 10.1b 分析:Chipscope Pro 三:设计流程 逻辑: 首先当然是RTL级设计,俗称硬件逻辑设计.使用的是Uedit32,这个软件相当于一个记事本,但编辑功能十分强大,简直是写Verilog代码的神器,具

php页面get方法实现ajax,入门实例教程

ajax,入门实例教程 本例针对php页面,做了一个小的demo加深对ajax的理解 1.文档结构: 共有ajax.php 和action.php 2个页面. 2.源码如下: /*ajax.php页面*/<!DOCTYPE html> <html lang="en"> <head> <title> ajax</title> <script type="text/javascript"> func

Omnet++ 4.0 入门实例教程

http://blog.sina.com.cn/s/blog_8a2bb17d01018npf.html 在网上找到的一个讲解omnet++的实例, 是4.0下面实现的. 我在4.2上试了试,可以用.照着做就能完成,有些小地方不同而已 Omnet++ 4.0 入门实例教程根据http://omnest.com/webdemo/ide 上的实例,自己动手做了做.新版本的4.0 跟它视频上的版本有些差别,配图说明一下我的操作过程,供大家一起学习.现在开始.首先,开发环境选择simulation 的视

freemarker入门实例与源码研究准备工作

首先去freemarker官网下载源码jar包,本文是基于freemarker-2.3.21.tar.gz进行研究的.解压源码包,找到freemarker的源码部分导入eclipse工程中.需要注意的是:freemarker的ftl文件解析使用javacc实现的,所以源码中没有解析类(FMParse.java).要想研究freemarker源码,往往还需要引入freemarker.jar(含有FMParse.class),否则源码会出现编译问题.另外,还需要引入的jar包有:commons-lo

Android HttpGet() 请求简单入门实例

HttpClient httpclient = new DefaultHttpClient(); String url = "http://example.com"; List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add( new BasicNameValuePair( "param", "value" ) ); URI uri =