背景:

工作任务完成后,闲暇之计给自己充充电!
Lucene是一个纯java全文检索工具包,采用倒排索引原理。
全文检索:指的是计算机索引程序通过扫描文章的每一个词,对每一个词建立一个索引,并指明该词在文章中出现的次数和位置。
索引的类型分为:1:为一索引、2:主键索引、3:聚集索引。索引就是加快检索表中数据的方法。
搜索:
    一:按被搜索的资源类型
    1、可以转为文本的
    2、多媒体类型的
    二:按照搜索方式:
    1、不处理语义,只是找出现了指定词语的所有文本。(指对词语进行匹配)
基本概念:
    1、使用流程:先建立索引,(索引库)在进行搜索。
    2、使用Lucene的数据结构,document、field。
建立索引的过程:
    1、定义一个语法分词器
    2、确定索引存储的位置
    3、创建IndexWriter,进行索引的写入
    4、内容提取,进行索引文件的写入
    5、关闭indexWriter
从索引库中搜索的过程:
    1、打开存储位置
    2、创建搜索器
    3、类似SQL进行查询
    4、处理结果
    5、关闭DirectoryReader
-----------------------------------------------------------------------------------------------------------------
 
 
  1. /**
  2. * @项目名称:lucene
  3. * @类名称:Article
  4. * @类描述:这是一个文章实体类
  5. * @创建人:YangChao
  6. * @创建时间:2016年8月30日 下午3:11:38
  7. * @version 1.0.0
  8. */
  9. public class Article {
  10. private Integer id;
  11. private String title;
  12. private String content;
  13. }
  1. /**
  2. * @项目名称:lucene
  3. * @类名称:DocumentUtils
  4. * @类描述:文章实体类和Document的转换工具
  5. * @创建人:YangChao
  6. * @创建时间:2016年8月31日 上午10:15:22
  7. * @version 1.0.0
  8. */
  9. public class DocumentUtils {
  10. public static Document article2Document(Article article) {
  11. Document doc = new Document();
  12. doc.add(new Field("id", article.getId().toString(), TextField.TYPE_STORED));
  13. doc.add(new Field("title", article.getTitle(), TextField.TYPE_STORED));
  14. doc.add(new Field("content", article.getContent(), TextField.TYPE_STORED));
  15. return doc;
  16. }
  17. public static Article document2Ariticle(Document doc) {
  18. Article article = new Article();
  19. article.setId(Integer.parseInt(doc.get("id")));
  20. article.setTitle(doc.get("title"));
  21. article.setContent(doc.get("content"));
  22. return article;
  23. }
  24. }
  1. /**
  2. * @项目名称:lucene
  3. * @类名称:LuceneUtils
  4. * @类描述:获取分词器和索引位置
  5. * @创建人:YangChao
  6. * @创建时间:2016年8月31日 上午9:48:06
  7. * @version 1.0.0
  8. */
  9. public class LuceneUtils {
  10. private static Logger logger = Logger.getLogger(LuceneUtils.class);
  11. private static Directory directory;
  12. private static Analyzer analyzer;
  13. static {
  14. try {
  15. directory = FSDirectory.open(Paths.get("./tmp/testindex"));
  16. // analyzer = new StandardAnalyzer();
  17. analyzer = new SmartChineseAnalyzer();
  18. } catch (Exception e) {
  19. logger.error("LuceneUtils error!", e);
  20. }
  21. }
  22. public static Directory getDirectory() {
  23. return directory;
  24. }
  25. public static Analyzer getAnalyzer() {
  26. return analyzer;
  27. }
  28. public static void closeIndexWriter(IndexWriter indexWriter) {
  29. if (indexWriter != null) {
  30. try {
  31. indexWriter.close();
  32. } catch (Exception e2) {
  33. logger.error("indexWriter.close error", e2);
  34. }
  35. }
  36. }
  37. }
  1. **
  2. * @项目名称:lucene
  3. * @类名称:QueryResult
  4. * @类描述:结果集
  5. * @创建人:YangChao
  6. * @创建时间:2016年8月31日 下午4:56:24
  7. * @version 1.0.0
  8. */
  9. public class QueryResult {
  10. private int count;
  11. private List list;
  12. public QueryResult() {
  13. super();
  14. }
  15. public QueryResult(int count, List list) {
  16. super();
  17. this.count = count;
  18. this.list = list;
  19. }
  20. }
  1. /**
  2. * @项目名称:lucene
  3. * @类名称:IndexDao
  4. * @类描述:
  5. * @创建人:YangChao
  6. * @创建时间:2016年8月31日 上午10:12:05
  7. * @version 1.0.0
  8. */
  9. public class IndexDao {
  10. private static Logger logger = Logger.getLogger(IndexDao.class);
  11. public void save(Article article) {
  12. Document doc = DocumentUtils.article2Document(article);
  13. IndexWriter indexWriter = null;
  14. try {
  15. IndexWriterConfig config = new IndexWriterConfig(LuceneUtils.getAnalyzer());
  16. indexWriter = new IndexWriter(LuceneUtils.getDirectory(), config);
  17. indexWriter.addDocument(doc);
  18. } catch (Exception e) {
  19. logger.error("IndexDao.save error", e);
  20. } finally {
  21. LuceneUtils.closeIndexWriter(indexWriter);
  22. }
  23. }
  24. public void delete(String id) {
  25. IndexWriter indexWriter = null;
  26. try {
  27. Term term = new Term("id", id);
  28. IndexWriterConfig config = new IndexWriterConfig(LuceneUtils.getAnalyzer());
  29. indexWriter = new IndexWriter(LuceneUtils.getDirectory(), config);
  30. indexWriter.deleteDocuments(term);// 删除含有指定term的所有文档
  31. } catch (Exception e) {
  32. logger.error("IndexDao.save error", e);
  33. } finally {
  34. LuceneUtils.closeIndexWriter(indexWriter);
  35. }
  36. }
  37. public void update(Article article) {
  38. Document doc = DocumentUtils.article2Document(article);
  39. IndexWriter indexWriter = null;
  40. try {
  41. Term term = new Term("id", article.getId().toString());
  42. IndexWriterConfig config = new IndexWriterConfig(LuceneUtils.getAnalyzer());
  43. indexWriter = new IndexWriter(LuceneUtils.getDirectory(), config);
  44. indexWriter.updateDocument(term, doc);// 先删除,后创建。
  45. } catch (Exception e) {
  46. logger.error("IndexDao.save error", e);
  47. } finally {
  48. LuceneUtils.closeIndexWriter(indexWriter);
  49. }
  50. }
  51. public QueryResult search(String queryString, int firstResult, int maxResult) {
  52. List<Article> list = new ArrayList<Article>();
  53. try {
  54. DirectoryReader ireader = DirectoryReader.open(LuceneUtils.getDirectory());
  55. // 2、第二步,创建搜索器
  56. IndexSearcher isearcher = new IndexSearcher(ireader);
  57. // 3、第三步,类似SQL,进行关键字查询
  58. String[] fields = { "title", "content" };
  59. QueryParser parser = new MultiFieldQueryParser(fields, LuceneUtils.getAnalyzer());
  60. Query query = parser.parse("检索");
  61. TopDocs topDocs = isearcher.search(query, firstResult + maxResult);
  62. int count = topDocs.totalHits;// 总记录数
  63. System.out.println("总记录数为:" + topDocs.totalHits);// 总记录数
  64. ScoreDoc[] hits = topDocs.scoreDocs;// 第二个参数,指定最多返回前n条结果
  65. // 高亮
  66. Formatter formatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");
  67. Scorer source = new QueryScorer(query);
  68. Highlighter highlighter = new Highlighter(formatter, source);
  69. // 摘要
  70. //          Fragmenter fragmenter = new SimpleFragmenter(5);
  71. //          highlighter.setTextFragmenter(fragmenter);
  72. // 处理结果
  73. int endIndex = Math.min(firstResult + maxResult, hits.length);
  74. for (int i = firstResult; i < endIndex; i++) {
  75. Document hitDoc = isearcher.doc(hits[i].doc);
  76. Article article = DocumentUtils.document2Ariticle(hitDoc);
  77. //
  78. String text = highlighter.getBestFragment(LuceneUtils.getAnalyzer(), "content", hitDoc.get("content"));
  79. if (text != null) {
  80. article.setContent(text);
  81. }
  82. list.add(article);
  83. }
  84. ireader.close();
  85. return new QueryResult(count, list);
  86. } catch (Exception e) {
  87. logger.error("IndexDao.search error", e);
  88. }
  89. return null;
  90. }
  91. }
  92. lucence详细学习地址:http://www.cnblogs.com/zhuxiaojie/p/5277219.html

全文检索lucene6.1的检索方式的更多相关文章

  1. Hibernate —— HQL、QBC检索方式

    一.HQL 检索方式 以双向的一对多来测试 HQL 检索方式.以 Department 和 Employee 为例. 建表语句: CREATE TABLE department ( dept_id ) ...

  2. Hibernate的检索方式

    Hibernate的检索方式 检索方式(查询的方式) 导航对象图检索方式: 根据已经加载的对象导航到其他对象 Customer customer = (Customer)session.get(Cus ...

  3. 攻城狮在路上(壹) Hibernate(十四)--- Hibernate的检索方式(下)

    本节介绍HQL和QBC的高级用法:各种连接查询.投影查询.报表查询.动态查询.集合过滤和子查询等.另外将归纳优化查询程序代码,从而提高查询性能的各种技巧.一.连接查询: HQL与QBC支持的各种连接类 ...

  4. 攻城狮在路上(壹) Hibernate(十三)--- Hibernate的检索方式(上)

    Hibernate提供了以下几种检索对象的方式: A.导航对象图检索方式. B.OID检索方式.Session.get() load(); C.HQL检索方式.Query. D.QBC检索方式.Que ...

  5. hibernate检索方式(HQL 检索方式,QBC 检索方式,本地 SQL 检索方式)

    hibernate有五种检索方式,这儿用 单向的一对多的映射关系 例子,这儿有后三种的方式: 导航对象图检索方式: 根据已经加载的对象导航到其他对象 OID 检索方式: 按照对象的 OID 来检索对象 ...

  6. Hibernate 检索方式

    概述 •Hibernate 提供了以下几种检索对象的方式 –导航对象图检索方式:  根据已经加载的对象导航到其他对象 –OID 检索方式:  按照对象的 OID 来检索对象 –HQL 检索方式: 使用 ...

  7. Hibernate入门6.Hibernate检索方式

    Hibernate入门6.Hibernate检索方式 20131128 代码下载 链接: http://pan.baidu.com/s/1Ccuup 密码: vqlv Hibernate的整体框架已经 ...

  8. [原创]java WEB学习笔记89:Hibernate学习之路-- -Hibernate检索方式(5种),HQL介绍,实现功能,实现步骤,

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  9. Hibernate的三种常用检索方式

    Hibernate 提供了以下几种检索对象的方式 ¨       导航对象图检索方式:  根据已经加载的对象导航到其他对象 ¨       OID 检索方式:  按照对象的 OID 来检索对象 ¨   ...

随机推荐

  1. sass揭秘之@mixin,%,@function(转载)

    因为文章内含有很多sass代码,如需自己动手查看编译结果,推荐使用sassmeister这款在线编译工具,方便你阅读学习. 在阅读本文章之前,请先确认你已经阅读了上篇文章sass揭秘之变量,不然会给你 ...

  2. VA Code编写html(1)

    <html> <head> <title>my webside</title> <!--win+‘/’注释行--> <!--防止中文乱 ...

  3. day25-1 time,datetime模块

    目录 time 为什么要有time模块,time模块有什么用 时间戳形式 格式化时间 结构化时间 各种时间格式互相转换 datetime 为什么要有datetime模块,detatime模块有什么用 ...

  4. SyntaxError Non-ASCII character '\xe5' in file

    环境: windows7 Python 2.7.16 在源码中添加注释之后报错如下: (WeChat) E:\WorkHome\Wechat>python firstBlood.py Trace ...

  5. 嵌入式 ThriftServer in Spark

    我们知道在Spark中可以通过start-thriftServer.sh 来启动ThriftServer,之后并可以通过beeline或者JDBC来连接并执行Spark SQL.在一般的Spark应用 ...

  6. 树状数组||归并排序求逆序对+离散化 nlogn

    我好咸鱼. 归并排序之前写过,树状数组就是维护从后往前插入,找比现在插入的数大的数的数量. 如果值域大,可以离散化 #include <cstdio> #include <cstri ...

  7. maven 依赖的传递性

    1.如图我们有三个项目,项目Age,项目Bge,项目Cge 2.我们使Age项目依赖到Bge项目,Bge项目依赖到Cge项目 Age项目和Bge项目分别执行命令:mvn install  打包*.ja ...

  8. 【codeforces 727D】T-shirts Distribution

    [题目链接]:http://codeforces.com/problemset/problem/727/D [题意] 给你6种尺寸的衣服; 他们的尺码依次为S, M, L, XL, XXL, XXXL ...

  9. asp.net MVC 自定义模型绑定 从客户端中检测到有潜在危险的 Request.QueryString 值

    asp.net mvc 自定义模型绑定 有潜在的Requset.Form 自定义了一个模型绑定器.前端会传过来一些敏感字符.调用bindContext. valueProvider.GetValue( ...

  10. static类型autowired 注入失败

    原代码:注入commonService对象失败 @Autowired private static CommonService commonService; public static List< ...