package com.bc.cas.manager;

import com.bc.cas.dao.BookDao;
import com.bc.cas.model.entity.Book;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import org.apache.log4j.helpers.LogLog;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


/**
 * @Copyright 2012-2016 duenboa 版权所有
 * @Author Created by Administrator on 2016/11/29.
 * @Version V 1.0.0
 * @Desc 索引管理器
 */

@Repository
public class IndexManager {

    @Autowired
    private BookDao bookDao;

    static FSDirectory dir;

    static {
        try {
            dir = FSDirectory.open(Paths.get("d:/lucene/lucene052_index05"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建索引 -common
     */
    @Test
    public void createIndex(List<Document> docs) throws IOException {

        if (docs == null) {
            return;
        }

        // 自定义停用词
        List<String> strings = Arrays.asList("的", "在", "了", "呢", ",", "0", ":", ",", "是", "这", "那", "么");
        CharArraySet unUsefulWorlds = new CharArraySet(strings, true);

        // 加入系统默认停用词
        Iterator<Object> itor = SmartChineseAnalyzer.getDefaultStopSet().iterator();
        while (itor.hasNext()) unUsefulWorlds.add(itor.next());
        //指定了停用词的分词器
        Analyzer analyzer = new SmartChineseAnalyzer(unUsefulWorlds);

        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        IndexWriter writer = new IndexWriter(dir, config);

        writer.addDocuments(docs);
        writer.commit();
        writer.close();
    }


    /**
     * 执行查询 -common
     *
     * @param query
     * @throws IOException
     * @throws ParseException
     */
    private static void doQuery(Query query) throws IOException, ParseException {
        IndexReader reader = DirectoryReader.open(dir);
        IndexSearcher searcher = new IndexSearcher(reader);

        //执行query,获取指定条数的顶行记录
        TopDocs topDocs = searcher.search(query, 10);
        System.out.println("搜索出的总记录数为: " + topDocs.totalHits);

        //评分文档集合
        ScoreDoc[] docs = topDocs.scoreDocs;
        for (ScoreDoc doc : docs) {
            //获取文档id
            int id = doc.doc;
            //根据文档id查询文档对象
            Document document = searcher.doc(id);

            //打印信息
            System.out.println(
                    Objects.toStringHelper("docuemnt")
                            .add("文档id", document.get("id"))
                            .add("文档名称", document.get("name"))
                            .add("文档图片", document.get("pic"))
                            .add("文档描述", document.get("description"))
                            .toString());
        }
        reader.close();
    }


    /**
     * 测试新建索引
     */
    public void testCreateIndex() {
        List<Book> bookList = bookDao.findAll();
        if (CollectionUtils.isEmpty(bookList)) return;

        List<Document> docList = Lists.newArrayList();
        Document doc;
        for (Book book : bookList) {
            doc = new Document();
            doc.add(new StoredField("id", book.getId()));
            doc.add(new StringField("name", book.getName(), Field.Store.YES));
            doc.add(new TextField("pic", book.getPic(), Field.Store.YES));
            doc.add(new TextField("description", book.getDescription(), Field.Store.YES));
            docList.add(doc);
        }

        try {
            createIndex(docList);
        } catch (IOException e) {
            LogLog.error(e.getMessage(), e);
        }
    }

    /**
     *
     * 查询
     *
     * @throws IOException
     */
    @Test
    public static void testQuery() throws IOException, ParseException {
        QueryParser parser = new QueryParser("description", new SmartChineseAnalyzer());
        Query query = parser.parse("description:java AND lucene");
        doQuery(query);
    }


}




Field类的子类和说明, 以及用法:

StoredField(FieldName, FieldValue) 

重载,支持多种类型
 不分词
不索引 
示例:
StringField(FieldName,  String FieldValue, Store.YES)

 字符串类型数据 
不分词    
索引 
示例: 订单号, id, 手机号等
LongField(FieldName, Long FieldValue,   Store.YES) 

Long型数据    
 分词
索引 
 示例: 价格
TextField(FieldName, FieldValue, Store.YES)    或 TextField(FieldName, Reader)

字符串或者流 
 分词
索引 














lucene 5.2.0学习笔记的更多相关文章

  1. DirectX 总结和DirectX 9.0 学习笔记

    转自:http://www.cnblogs.com/graphics/archive/2009/11/25/1583682.html DirectX 总结 DDS DirectXDraw Surfac ...

  2. 一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移

    不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.superviso ...

  3. vue2.0学习笔记之路由(二)路由嵌套+动画

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. vue2.0学习笔记之路由(二)路由嵌套

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  5. hdcms v5.7.0学习笔记

    hdcms v5.7.0学习笔记 https://note.youdao.com/ynoteshare1/index.html?id=c404d63ac910eb15a440452f73d6a6db& ...

  6. dhtmlxgrid v3.0学习笔记

    dhtmlxgrid v3.0学习笔记 分类: dhtmlx JavaScript2012-01-31 15:41 1744人阅读 评论(0) 收藏 举报 stylesheetdatecalendar ...

  7. OAuth 2.0学习笔记

    文章目录 OAuth的作用就是让"客户端"安全可控地获取"用户"的授权,与"服务商提供商"进行互动. OAuth在"客户端&quo ...

  8. 一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx、supervisor、mysql环境搭建

    作为.neter,看到.net core 2.0的正式发布,心里是有点小激动的,迫不及待的体验了一把,发现速度确实是快了很多,其中也遇到一些小问题,所以整理了一些学习笔记: 阅读目录 环境说明 安装C ...

  9. RxJava2.0学习笔记2 2018年7月3日 周二

    摘记: 1.map -- 转换  有些服务端的接口设计,会在返回的数据外层包裹一些额外信息,这些信息对于调试很有用,但本地显示是用不到的.使用 map() 可以把外层的格式剥掉,只留下本地会用到的核心 ...

随机推荐

  1. ubuntu环境下安装Redis

    1.命令行安装 sudo apt-get update sudo apt-get install redis-server 2.启动redis $redis-server :C Aug ::42.26 ...

  2. SQL必知必会 记录

    登录数据库mysql -u root -p查看所有数据库  show databases:选择数据库  use 数据库名:查看所有表      show tables查看表结构      descri ...

  3. linux服务器应用NTP配置时间同步

    linux服务器应用NTP配置时间同步 • 为什么建议使用ntpd而不是ntpdate? #####原因很简单,ntpd是步进式的逐渐调整时间,而ntpdate是断点更新,比如现在服务器时间是9.18 ...

  4. Java 反射机制应用实践

    反射基础 p.s: 本文需要读者对反射机制的API有一定程度的了解,如果之前没有接触过的话,建议先看一下官方文档的Quick Start(https://docs.oracle.com/javase/ ...

  5. jspm

    1.简介 JavaScript 模块的写法有几种,比如 AMD,CommonJS .. 还有标准化的 ES6 的写法 .. jspm 支持加载所有的用这些方法写的 JavaScript 模块 在你的应 ...

  6. HDU3518Boring counting(后缀自动机)

    Problem Description 035 now faced a tough problem,his english teacher gives him a string,which consi ...

  7. nodejs渲染到页面的理解

    一般逻辑都是: 打开页面,前端发请求到服务端,服务端返回数据到前端,前端根据数据生成DOM节点,然后append到DOM中. 如果是nodejs渲染到页面,我的理解是: 打开页面,服务端直接把数据查询 ...

  8. xftp连接不上阿里云服务器

    打开xftp默认是使用FTP协议,要连接到云服务器,需要将协议改为SFTP 连接成功

  9. Win8 安装.Net Framework3.5(2.0,3.0)组件二种方式

    第一种: 通过命令+win8映像文件 找到系统盘cmd文件:C:\WINDOWS\system32\Cmd.exe 右键“以管理员身份运行”,然后弹出一个黑框框. 黑框框里面输入一下命令: dism. ...

  10. 2015 浙江省赛 Beauty of Array (思维题)

    Beauty of Array Edward has an array A with N integers. He defines the beauty of an array as the summ ...