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. js抽象工厂模式

    抽象工厂模式,提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类. 抽象工厂允许客户使用抽象的接口来创建一组相关产品,而不需要知道或关心实际生产出的具体产品是什么.这样客户就可以从具体 ...

  2. 数据库排序规则的冲突(理解collate Chinese_PRC_CI_AS)

    之前碰到了数据库排序规则冲突问题,即百度或者 Google 的老话题: “ 无法解决 equal to 操作中‘ sql_latin1_general_cp1_ci_as ’和‘ chinese_pr ...

  3. php:使用XHProf查找PHP性能瓶颈

    https://www.cnblogs.com/casatwy/archive/2013/01/17/2865241.html XHProf是facebook 开发的一个测试php性能的扩展,本文记录 ...

  4. Highcharts中更新series的5种方法

    用Highcharts画图时,经常需要更新所画的图表,最常见的就是改变数据以更新图表.在Highcarts中,数据对应的参数是series.这儿就以图1的柱状图为例,列举如何更新series的5种方法 ...

  5. maven笔记(maven使用与安装,eclipse中maven的配置,maven项目的创建)

    一.初识maven 1.maven是什么? 他是一个项目管理器,配置好pom配置文件后,maven会管理项目的依赖文件等,当项目用到外部jar包时,maven帮助我们去网上下载并打包发到Tomcat中 ...

  6. 分布式_理论_07_ZAB

    一.前言 二.参考资料 1.分布式理论(七)—— 一致性协议之 ZAB

  7. Debian For ARM Webmin Server

    /******************************************************************************** * Debian For ARM W ...

  8. ASP.NET MVC 缓存Outputcache (局部动态)

    首先说一下需求: 比如我需要对网站首页做缓存,于是在首页对于的Action上贴上了Outputcache,接着问题就来了,首页上的有部分数据是不能做缓存的,比如个人信息,不然,每个人登陆都是看到第一个 ...

  9. 超时 CS-8610 中性笔

    超时 CS-8610 中性笔 最初觉得这款笔很简单,而且还认为有点丑,因为笔头比较短. 比较特别提这款中性笔比一般的中性笔要粗一点. 使用后才发现比其它的中性笔好用,因为笔杆粗,手感好,笔杆上并没有特 ...

  10. MySQL自带的性能压力测试工具mysqlslap详解

    使用语法如下:# mysqlslap [options] 常用参数 [options] 详细说明: --auto-generate-sql, -a 自动生成测试表和数据,表示用mysqlslap工具自 ...