1.创建索引

  

  1. package com.DingYu.Test;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.io.UnsupportedEncodingException;
  8. import java.nio.file.Paths;
  9.  
  10. import org.apache.lucene.analysis.Analyzer;
  11. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  12. import org.apache.lucene.document.Document;
  13. import org.apache.lucene.document.Field;
  14. import org.apache.lucene.document.Field.Store;
  15. import org.apache.lucene.document.StoredField;
  16. import org.apache.lucene.index.IndexWriter;
  17. import org.apache.lucene.index.IndexWriterConfig;
  18. import org.apache.lucene.store.Directory;
  19. import org.apache.lucene.store.FSDirectory;
  20. import org.junit.Test;
  21.  
  22. /**
  23. * 我们的目标是把索引和文档存入索引库中, 所以首先我们需要创建一个索引库 然后创建一个IndexWrite对象把索引,和文档对象写入,
  24. * 文档对象中需要自己设置域,索引是通过分词器对域进行分词产生的, 所以我们需要分词器
  25. *
  26. * @author 丁宇
  27. *
  28. */
  29. public class LuceneTest {
  30. /**
  31. * 创建索引
  32. * @throws IOException
  33. */
  34. @Test
  35. public void createIndex() throws IOException {
  36. // 标准分词器
  37. Analyzer analyzer = new StandardAnalyzer();
  38. // 创建一个索引
  39. Directory directory = FSDirectory.open(Paths.get("D:\\LuceneIndex"));
  40. // 创建一个IndexWriteConfig对象
  41. IndexWriterConfig config = new IndexWriterConfig(analyzer);
  42. // 创建一个IndexWrite对象
  43. IndexWriter write = new IndexWriter(directory, config);
  44. // 获得所有文件下的文件
  45. File[] files = new File("D:\\LuceneTest").listFiles();
  46. for (File file : files) {
  47. // 创建一个文档对象
  48. Document document = new Document();
  49. // 增加一个filepath域,不分析 不索引 但会存储在索引库里 把文件路径放到域中
  50. Field field1 = new StoredField("filepath", file.getPath());
  51. // 增加一个filename域,会分词,会索引,
  52. Field field2 = new org.apache.lucene.document.TextField("filename", file.getName(), Store.YES);
  53. // 增加一个fileContent域,会分词,会索引,只放文件内容的索引
  54. Field field3 = new org.apache.lucene.document.TextField("filecontent", fileContent(file), Store.NO);
  55. // 增加一个filesize域,不分析 不索引 但会存储在索引库里 把文件路径放到域中
  56. Field field4 = new StoredField("filesize", file.length());
  57. document.add(field1);
  58. document.add(field2);
  59. document.add(field3);
  60. document.add(field4);
  61. write.addDocument(document);
  62. }
  63. write.close();
  64. }
  65. /**
  66. * 获得文件内容
  67. * @param file
  68. * @return
  69. */
  70. public String fileContent(File file) {
  71. byte[] fileContent = new byte[(int) file.length()];
  72. FileInputStream in = null;
  73. try {
  74. in = new FileInputStream(file);
  75. } catch (FileNotFoundException e2) {
  76. e2.printStackTrace();
  77. }
  78. try {
  79. in.read(fileContent);
  80. } catch (IOException e1) {
  81. e1.printStackTrace();
  82. }
  83. try {
  84. in.close();
  85. } catch (IOException e) {
  86. e.printStackTrace();
  87. }
  88. try {
  89. return new String(fileContent, "UTF-8");
  90. } catch (UnsupportedEncodingException e) {
  91. e.printStackTrace();
  92. }
  93. return null;
  94. }
  95. }

2.查询索引

  1. package com.DingYu.Test;
  2.  
  3. import java.io.IOException;
  4. import java.nio.file.Path;
  5. import java.nio.file.Paths;
  6.  
  7. import org.apache.lucene.document.Document;
  8. import org.apache.lucene.index.DirectoryReader;
  9. import org.apache.lucene.index.IndexReader;
  10. import org.apache.lucene.index.Term;
  11. import org.apache.lucene.search.BooleanClause.Occur;
  12. import org.apache.lucene.search.BooleanQuery;
  13. import org.apache.lucene.search.IndexSearcher;
  14. import org.apache.lucene.search.NumericRangeQuery;
  15. import org.apache.lucene.search.Query;
  16. import org.apache.lucene.search.ScoreDoc;
  17. import org.apache.lucene.search.TermQuery;
  18. import org.apache.lucene.search.TopDocs;
  19. import org.apache.lucene.store.Directory;
  20. import org.apache.lucene.store.FSDirectory;
  21. import org.junit.Test;
  22.  
  23. /**
  24. * 查询索引
  25. *
  26. * @author 丁宇
  27. *
  28. */
  29. public class LuceneTest1 {
  30. // 获得IndexSearcher对象
  31. private IndexSearcher getIndexSearcher() throws IOException {
  32. // 指定索引库
  33. Directory directory = FSDirectory.open(Paths.get("D:\\LuceneIndex"));
  34. // 打开索引库
  35. IndexReader reader = DirectoryReader.open(directory);
  36. // 创建查询的对象
  37. IndexSearcher searcher = new IndexSearcher(reader);
  38. return searcher;
  39. }
  40.  
  41. // 输出查到的内容
  42. private void printIndex(TopDocs docs,IndexSearcher searcher) throws IOException {
  43. // 获得顶部匹配记录
  44. ScoreDoc[] scoreDocs = docs.scoreDocs;
  45. // 获得在索引库中存着的文档的id,利用id去寻找文档
  46. for (ScoreDoc scoreDoc : scoreDocs) {
  47. // 获得id
  48. int doc = scoreDoc.doc;
  49. // 获得文档
  50. Document document = searcher.doc(doc);
  51. // 获得这个文档的域
  52. System.out.println(document.get("filename"));
  53. System.out.println(document.get("filecontent"));
  54. System.out.println(document.get("filepath"));
  55. System.out.println(document.get("filesize"));
  56. System.out.println("------------------------");
  57. }
  58. }
  59. /**
  60. * 精准查询
  61. * @throws IOException
  62. */
  63. @Test
  64. public void termQueryIndex() throws IOException {
  65.  
  66. IndexSearcher searcher = getIndexSearcher();
  67. // 选择合适的查询方法,这里用最简单的,具体的看下图
  68. Query query = new TermQuery(new Term("filename", "txt"));
  69. // 执行查询
  70. TopDocs docs = searcher.search(query, 2);
  71. //输出查询内容
  72. printIndex(docs, searcher);
  73. // 关闭索引库
  74. searcher.getIndexReader().close();
  75. }
  76. /**
  77. * 范围查询 五个参数 第一个域名,第二个第三个表示范围,第四个第五个表示是否包含最小值和最大值。
  78. * @throws IOException
  79. */
  80. @Test
  81. public void numRangeQueryIndex() throws IOException {
  82. IndexSearcher searcher = getIndexSearcher();
  83. // 选择合适的查询方法,这里用最简单的,具体的看下图
  84. Query query = NumericRangeQuery.newLongRange("filesize", 0L, 1000L, true, true);
  85. // 执行查询
  86. TopDocs docs = searcher.search(query, 2);
  87. //输出查询内容
  88. printIndex(docs, searcher);
  89. // 关闭索引库
  90. searcher.getIndexReader().close();
  91. }
  92. /**
  93. * 组合查询
  94. * @throws IOException
  95. */
  96. @Test
  97. public void booleanQueryIndex() throws IOException {
  98. IndexSearcher searcher = getIndexSearcher();
  99. BooleanQuery booleanQuery = new BooleanQuery();
  100. Query query = new TermQuery(new Term("filename","txt"));
  101. Query query2 = NumericRangeQuery.newLongRange("filesize", 0L, 1000L, true, true);
  102. //表示query是必须的 query2也是必须 相当于并集
  103. booleanQuery.add(query,Occur.MUST);
  104. booleanQuery.add(query2, Occur.MUST);
  105. // 执行查询
  106. TopDocs docs = searcher.search(query, 2);
  107. //输出查询内容
  108. printIndex(docs, searcher);
  109. // 关闭索引库
  110. searcher.getIndexReader().close();
  111. }
  112. }

3.删除索引

  1. package com.DingYu.Test;
  2.  
  3. import java.io.IOException;
  4. import java.nio.file.Paths;
  5.  
  6. import org.apache.lucene.analysis.Analyzer;
  7. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  8. import org.apache.lucene.index.IndexWriter;
  9. import org.apache.lucene.index.IndexWriterConfig;
  10. import org.apache.lucene.index.Term;
  11. import org.apache.lucene.search.Query;
  12. import org.apache.lucene.search.TermQuery;
  13. import org.apache.lucene.store.Directory;
  14. import org.apache.lucene.store.FSDirectory;
  15. import org.junit.Test;
  16.  
  17. /**
  18. * 删除索引 一般增删改都是同一个操作对象 这里使用IndexWriter对象
  19. *
  20. * @author 丁宇
  21. *
  22. */
  23. public class LuceneTest3 {
  24. /**
  25. * 获得IndexWrite对象
  26. * @return
  27. * @throws IOException
  28. */
  29. public IndexWriter getIndexWrite() throws IOException {
  30. Analyzer analyzer = new StandardAnalyzer();
  31. Directory directory = FSDirectory.open(Paths.get("D:\\LuceneIndex"));
  32. IndexWriterConfig config = new IndexWriterConfig(analyzer);
  33. return new IndexWriter(directory, config);
  34. }
  35.  
  36. /**
  37. * 删除所有的索引
  38. *
  39. * @throws IOException
  40. */
  41. @Test
  42. public void deleteAllIndex() throws IOException {
  43. IndexWriter indexWrite = getIndexWrite();
  44. indexWrite.deleteAll();
  45. indexWrite.close();
  46. }
  47. /**
  48. * 根据条件删除索引,同时删除文档
  49. * @throws IOException
  50. */
  51. @Test
  52. public void deleteSomeIndex() throws IOException {
  53. IndexWriter indexWrite = getIndexWrite();
  54. Query query = new TermQuery(new Term("filename","txt"));
  55. indexWrite.deleteDocuments(query);
  56. indexWrite.close();
  57. }
  58. }

4.修改索引

  1. package com.DingYu.Test;
  2.  
  3. import java.io.IOException;
  4. import java.nio.file.Paths;
  5.  
  6. import org.apache.lucene.analysis.Analyzer;
  7. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  8. import org.apache.lucene.document.Document;
  9. import org.apache.lucene.document.Field.Store;
  10. import org.apache.lucene.document.StringField;
  11. import org.apache.lucene.index.IndexWriter;
  12. import org.apache.lucene.index.IndexWriterConfig;
  13. import org.apache.lucene.index.IndexableField;
  14. import org.apache.lucene.index.Term;
  15. import org.apache.lucene.store.Directory;
  16. import org.apache.lucene.store.FSDirectory;
  17. import org.junit.Test;
  18.  
  19. /**
  20. * 索引的修改
  21. * @author 丁宇
  22. *
  23. */
  24. public class LuceneTest2 {
  25.  
  26. private IndexWriter getIndexWriter() throws IOException {
  27. Analyzer analyzer = new StandardAnalyzer();
  28. Directory directory = FSDirectory.open(Paths.get("D:\\LuceneIndex"));
  29. IndexWriterConfig config = new IndexWriterConfig(analyzer);
  30. return new IndexWriter(directory, config);
  31. }
  32.  
  33. @Test
  34. public void updateIndex() throws IOException {
  35. IndexWriter indexWriter = getIndexWriter();
  36. Document document = new Document();
  37. document.add(new StringField("filename", "think in java", Store.YES));
  38. //update 就是删除一个你指定的 创建一个你想要的 。
  39. indexWriter.updateDocument(new Term("filecontent","txt"), document);
  40. indexWriter.close();
  41. }
  42. }

Lucene的简单用法的更多相关文章

  1. 2、Lucene 最简单的使用(小例子)

    在了解了Lucene以后,我打算亲手来做一个Lucene的小例子,这个例子只是Lucene最简单的应用:使用Lucene实现标准的英文搜索: 1.下载Lucene 下载Lucene,到Lucene的官 ...

  2. CATransition(os开发之画面切换) 的简单用法

    CATransition 的简单用法 //引进CATransition 时要添加包“QuartzCore.framework”,然后引进“#import <QuartzCore/QuartzCo ...

  3. jquery.validate.js 表单验证简单用法

    引入jquery.validate.js插件以及Jquery,在最后加上这个插件的方法名来引用.$('form').validate(); <!DOCTYPE html PUBLIC " ...

  4. NSCharacterSet 简单用法

    NSCharacterSet 简单用法 NSCharacterSet其实是许多字符或者数字或者符号的组合,在网络处理的时候会用到 NSMutableCharacterSet *base = [NSMu ...

  5. [转]Valgrind简单用法

    [转]Valgrind简单用法 http://www.cnblogs.com/sunyubo/archive/2010/05/05/2282170.html Valgrind的主要作者Julian S ...

  6. Oracle的substr函数简单用法

    substr(字符串,截取开始位置,截取长度) //返回截取的字 substr('Hello World',0,1) //返回结果为 'H'  *从字符串第一个字符开始截取长度为1的字符串 subst ...

  7. Ext.Net学习笔记19:Ext.Net FormPanel 简单用法

    Ext.Net学习笔记19:Ext.Net FormPanel 简单用法 FormPanel是一个常用的控件,Ext.Net中的FormPanel控件同样具有非常丰富的功能,在接下来的笔记中我们将一起 ...

  8. TransactionScope简单用法

    记录TransactionScope简单用法,示例如下: void Test() { using (TransactionScope scope = new TransactionScope()) { ...

  9. WPF之Treeview控件简单用法

    TreeView:表示显示在树结构中分层数据具有项目可展开和折叠的控件 TreeView 的内容是可以包含丰富内容的 TreeViewItem 控件,如 Button 和 Image 控件.TreeV ...

随机推荐

  1. Python 列表详细使用

    1. 列表 列表是Python中内置有序.可变序列,列表的所有元素放在一对中括号“[]”中,并使用逗号分隔开: 当列表元素增加或删除时,列表对象自动进行扩展或收缩内存,保证元素之间没有缝隙: 在Pyt ...

  2. 教你一招用 IDE 编程提升效率的骚操作!

    阅读本文大概需要 3 分钟. IDEA 有个很牛逼的功能,那就是后缀补全(不是自动补全),很多人竟然不知道这个操作,还在手动敲代码. 这个功能可以使用代码补全来模板式地补全语句,如遍历循环语句(for ...

  3. Eclipse 中 Spring 项目的 XML 配置文件报错 Referenced file contains errors

    原来运行正常的项目,突然在applicationContext.xml 文件头报错 总结一下网上的解决方案: 1.有可能网络状况不好导致 如果使用Maven构建项目,spring在加载xsd文件时总是 ...

  4. lua入门demo(HelloWorld+redis读取)

    1. lua入门demo 1.1. 入门之Hello World!! 由于我习惯用docker安装各种软件,这次的lua脚本也是运行在docker容器上 openresty是nginx+lua的各种模 ...

  5. PHP之ThinkPHP框架(验证码、文件上传、图片处理)

     验证码 验证码是框架自带有的,比之前使用GD库简单方便许多,其实现原理基本相似,都是生成图片,保存验证码值到Session中,表单提交验证码,然后进行值的对比验证. 简单的显示: <form ...

  6. c++模板参数——数值类型推断

    模板类中,或模板函数中,若限定模板参数为数值类型,可以使用如下方式进行判断. template<typename T> Fmt::Fmt(const char *fmt, T val) { ...

  7. python常用库函数 - 备忘

    基础库 1. 正则表达式:re 符号 ()小括号 -- 分组 []中括号 -- 字符类,匹配所包含的任一字符 #注:字符集合把[]里面的内容当作普通字符!(-\^除外) {}大括号 -- 限定匹配次数 ...

  8. [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了

    [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 本文首发自:博客园 文章地址: https://www.cnblogs.com/yilezhu/p/ ...

  9. 并发服务器三种实现方式之进程、线程和select

    前言:刚开始学网络编程,都会先写一个客户端和服务端,不知道你们有没有试一下:再打开一下客户端,是连不上服务端的.还有一个问题不知道你们发现没:有时启服务器,会提示“Address already in ...

  10. ⑧javaWeb之在例子中学习(过滤器Filter)

    前言 本系列 Servlet & JSP 学习系列[传送门]逐渐到了中期了,希望大家喜欢我写的,总结的点点滴滴- 今天我们来讲讲过滤器 你们的支持是我写博客的动力哦. 最近买了两本书,觉得大二 ...