lucene5.0建立索引并进行查找

说白了就是两个函数一个建立索引(写),另一个来查找(读),所以涉及到java IO的一些知识。

[java] view plaincopyprint?

  1. import java.io.*;
  2. import java.nio.file.Paths;
  3. import java.util.Date;
  4. import org.apache.lucene.analysis.Analyzer;
  5. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  6. import org.apache.lucene.document.Document;
  7. import org.apache.lucene.document.Field;
  8. import org.apache.lucene.document.Field.Store;
  9. import org.apache.lucene.document.LongField;
  10. import org.apache.lucene.document.StringField;
  11. import org.apache.lucene.document.TextField;
  12. import org.apache.lucene.index.*;
  13. import org.apache.lucene.store.Directory;
  14. import org.apache.lucene.store.FSDirectory;
  15. /**
  16. * This class demonstrate the process of creating index with Lucene
  17. * for text files
  18. */
  19. public class TxtFileIndexer {
  20. public static void main(String[] args) throws Exception{
  21. //indexDir is the directory that hosts Lucene‘s index files
  22. Directory indexDir = FSDirectory.open(Paths.get("G:\\luceneout"));
  23. //dataDir is the directory that hosts the text files that to be indexed
  24. File   dataDir  = new File("G:\\downloads\\LJParser_release\\LJParser_Packet\\训练分类用文本\\交通");
  25. Analyzer luceneAnalyzer = new StandardAnalyzer(); //新建一个分词器实例
  26. IndexWriterConfig config = new IndexWriterConfig(luceneAnalyzer);
  27. File[] dataFiles  = dataDir.listFiles(); //所有训练样本文件
  28. IndexWriter indexWriter = new IndexWriter(indexDir,config);//构造一个索引写入器
  29. long startTime = new Date().getTime();
  30. for(int i = 0; i < dataFiles.length; i++){
  31. if(dataFiles[i].isFile() && dataFiles[i].getName().endsWith(".txt")){
  32. System.out.println("Indexing file " + dataFiles[i].getCanonicalPath()); //返回绝对路径
  33. Document document = new Document();//每一个文件都变成一个document对象
  34. Reader txtReader = new FileReader(dataFiles[i]);
  35. Field field1 = new StringField("path",dataFiles[i].getPath(),Store.YES);
  36. Field field2 = new TextField("content",txtReader);
  37. Field field3 = new LongField("fileSize", dataFiles[i].length(), Store.YES);
  38. Field field4 = new TextField("filename",dataFiles[i].getName(),Store.YES);
  39. document.add(field1);
  40. document.add(field2);
  41. document.add(field3);
  42. document.add(field4);
  43. indexWriter.addDocument(document); //写进一个索引
  44. }
  45. }
  46. //indexWriter.optimize();
  47. indexWriter.close();
  48. long endTime = new Date().getTime();
  49. System.out.println("It takes " + (endTime - startTime)
  50. + " milliseconds to create index for the files in directory "
  51. + dataDir.getPath());
  52. }
  53. }
import java.io.*; 
import java.nio.file.Paths;
import java.util.Date; 
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.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*; 
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/** 
* This class demonstrate the process of creating index with Lucene 
* for text files 
*/ 
public class TxtFileIndexer { 
     public static void main(String[] args) throws Exception{ 
     //indexDir is the directory that hosts Lucene‘s index files 
     Directory indexDir = FSDirectory.open(Paths.get("G:\\luceneout"));
     //dataDir is the directory that hosts the text files that to be indexed 
     File   dataDir  = new File("G:\\downloads\\LJParser_release\\LJParser_Packet\\训练分类用文本\\交通"); 
     Analyzer luceneAnalyzer = new StandardAnalyzer(); //新建一个分词器实例
     IndexWriterConfig config = new IndexWriterConfig(luceneAnalyzer);
     File[] dataFiles  = dataDir.listFiles(); //所有训练样本文件
     IndexWriter indexWriter = new IndexWriter(indexDir,config);//构造一个索引写入器 
     long startTime = new Date().getTime(); 
     for(int i = 0; i < dataFiles.length; i++){ 
          if(dataFiles[i].isFile() && dataFiles[i].getName().endsWith(".txt")){
               System.out.println("Indexing file " + dataFiles[i].getCanonicalPath()); //返回绝对路径
               Document document = new Document();//每一个文件都变成一个document对象 
               Reader txtReader = new FileReader(dataFiles[i]); 
               Field field1 = new StringField("path",dataFiles[i].getPath(),Store.YES);
               Field field2 = new TextField("content",txtReader);
               Field field3 = new LongField("fileSize", dataFiles[i].length(), Store.YES); 
               Field field4 = new TextField("filename",dataFiles[i].getName(),Store.YES);
               document.add(field1);
               document.add(field2);
               document.add(field3);
               document.add(field4);
               indexWriter.addDocument(document); //写进一个索引
          } 
     } 
     //indexWriter.optimize(); 
     indexWriter.close(); 
     long endTime = new Date().getTime(); 
        
     System.out.println("It takes " + (endTime - startTime) 
         + " milliseconds to create index for the files in directory "
         + dataDir.getPath());        
     } 
}

读取索引并查找

[java] view plaincopyprint?

  1. import java.io.File;
  2. import java.nio.file.Paths;
  3. import org.apache.lucene.analysis.standard.StandardAnalyzer;
  4. import org.apache.lucene.document.Document;
  5. import org.apache.lucene.index.DirectoryReader;
  6. import org.apache.lucene.queryparser.classic.QueryParser;
  7. import org.apache.lucene.search.*;
  8. import org.apache.lucene.store.*;
  9. /**
  10. * This class is used to demonstrate the
  11. * process of searching on an existing
  12. * Lucene index
  13. *
  14. */
  15. public class TxtFileSearcher {
  16. public static void main(String[] args) throws Exception{
  17. //存储了索引文件
  18. Directory indexDir = FSDirectory.open(Paths.get("G:\\luceneout"));
  19. //读取器读取索引文件
  20. DirectoryReader ireader = DirectoryReader.open(indexDir);
  21. //查找
  22. IndexSearcher searcher = new IndexSearcher(ireader);
  23. //目的查找字符串
  24. String queryStr = "大数据挖掘";
  25. //构造一个词法分析器,并将查询结果返回到一个队列
  26. QueryParser parser = new QueryParser("content",new StandardAnalyzer());
  27. Query query = parser.parse(queryStr);
  28. TopDocs docs = searcher.search(query, 100);
  29. System.out.print("一共搜索到结果:"+docs.totalHits+"条");
  30. //输出查询结果信息
  31. for(ScoreDoc scoreDoc:docs.scoreDocs){
  32. System.out.print("序号为:"+scoreDoc.doc);
  33. System.out.print("评分为:"+scoreDoc.score);
  34. Document document = searcher.doc(scoreDoc.doc);
  35. System.out.print("路径为:"+document.get("path"));
  36. System.out.print("内容为"+document.get("content"));
  37. System.out.print("文件大小为"+document.get("fileSize"));
  38. System.out.print("文件名为"+document.get("filename"));
  39. System.out.println();
  40. }
  41. }
  42. }
import java.io.File; 
import java.nio.file.Paths;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document; 
import org.apache.lucene.index.DirectoryReader;  
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*; 
import org.apache.lucene.store.*;
 /** 
 * This class is used to demonstrate the 
 * process of searching on an existing 
 * Lucene index 
 * 
 */ 
 public class TxtFileSearcher { 
	 public static void main(String[] args) throws Exception{ 
		 //存储了索引文件
		 Directory indexDir = FSDirectory.open(Paths.get("G:\\luceneout"));
		 //读取器读取索引文件
		 DirectoryReader ireader = DirectoryReader.open(indexDir);
		 //查找
		 IndexSearcher searcher = new IndexSearcher(ireader);
		 //目的查找字符串
		 String queryStr = "大数据挖掘";
		 //构造一个词法分析器,并将查询结果返回到一个队列
		 QueryParser parser = new QueryParser("content",new StandardAnalyzer());
		 Query query = parser.parse(queryStr);
		 TopDocs docs = searcher.search(query, 100);
		 System.out.print("一共搜索到结果:"+docs.totalHits+"条");
		 //输出查询结果信息
		 for(ScoreDoc scoreDoc:docs.scoreDocs){
			 System.out.print("序号为:"+scoreDoc.doc);
			 System.out.print("评分为:"+scoreDoc.score);
			 Document document = searcher.doc(scoreDoc.doc);
			 System.out.print("路径为:"+document.get("path"));
			 System.out.print("内容为"+document.get("content"));
			 System.out.print("文件大小为"+document.get("fileSize"));
			 System.out.print("文件名为"+document.get("filename"));
			 System.out.println();
		 }	 
	 } 
 }

运行结果

下面是文件目录

两个函数都需要用到分词器,前者是为了配置写入,后者则是为了配置词法分析器来查找

时间: 2024-07-30 20:21:18

lucene5.0建立索引并进行查找的相关文章

数据结构-查找-线性索引查找(对于无序顺序存储,建立索引快速查找)

1.索引 我们前面提到的几种高效查找方法都是基于有序的基础上的,但是实际上,很多数据集可能增长非常快.例如空间动态信息等,对于这样的查找表,我们若是保证记录全部按照当中某个关键字有序,其维护的时间代价非常高,所以这种数据通常是按照先后顺序存储. 数据结构的最终目的就是提高数据的处理速度,索引是为了加快查找速度而设计的一种数据结构.索引就是把一个关键字与他对应的记录相关联的过程. 一个索引由若干个索引项构成,每个索引项至少应包含关键字和其对应的记录在存储器中的位置等信息. 索引技术是组织大型数据库

lucene 建立索引与查询

Lucene 简介 Lucene 是一个基于 Java 的全文信息检索工具包,它不是一个完整的搜索应用程序,而是为你的应用程序提供索引和搜索功能.Lucene 目前是 Apache Jakarta 家族中的一个开源项目.也是目前最为流行的基于 Java 开源全文检索工具包. 目前已经有很多应用程序的搜索功能是基于 Lucene 的,比如 Eclipse 的帮助系统的搜索功能.Lucene 能够为文本类型的数据建立索引,所以你只要能把你要索引的数据格式转化的文本的,Lucene 就能对你的文档进行

数据库为何要建立索引的原因说明

数据库索引是为了增加查询速度而对表字段附加的一种标识.见过很多人机械的理解索引的概念,认为增加索引只有好处没有坏处. 这里想把之前的索引学习笔记总结一下: 首先明白为什么索引会增加速度,DB在执行一条Sql语句的时候,默认的方式是根据搜索条件进行全表扫描,遇到匹配条件的就加入搜索结果集合.如果我们对某一字段增加索引,查询时就会先去索引列表中一次定位到特定值的行数,大大减少遍历匹配的行数,所以能明显增加查询的速度.那么在任何时候都应该加索引么?这里有几个反例:1.如果每次都需要取到所有表记录,无论

Lucene建立索引然后搜索的小Demo

package junitTest; import java.io.IOException; import java.io.StringReader; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.luce

sqlite优化记录:建立索引加快查询速度

凡是数据库中,索引的存在就是为了提高查询速度的,数据库的索引有点类似于书本上面的目录的概念,因为在英文中都是index,事实上也就是目录. 其算法应该叫做“倒排索引”,这个其实也类似于搜索引擎里面的基本算法. 测试:10w条数据,没有索引的情况下,查询一条数据大约需要550ms以上. 建立索引后,数据库的体积增大了3倍左右,但是同样的查询却减少到8ms的级别,提升了70倍 有时候关于sqlite数据库出错或者没法用的情况看这里 下面是在android手机上面的测试代码 查看源代码 打印帮助 01

使用NOSQL的MongoDB时建立索引需要注意的几点建议和Explain优化分析

第一,MongoDB索引和MySQL索引非常相似并且对于MySQL的索引优化有很多也适用于MongoDB. 第二,更重要的是,这些索引的建立对你的应用提高也是有限的. 对于应用的最佳索引策略应该基于很多的重要因素.包含了你期望查询的类型, 数据读取与写入的比率,甚至于你服务器的空闲内存.意思就是, 需要对线上的产品做很多的测试剖析工作,才能调整出最佳的索引策略. 没有什么好的方法可以替代实际经验的. 索引策略 下面有些索引的基本法则 创建的索引要匹配查询. 如果你仅仅要查询单个字段.索引这个字段

Oracle 建立索引及SQL优化

Oracle 建立索引及SQL优化 数据库索引: 索引有单列索引 复合索引之说 如何某表的某个字段有主键约束和唯一性约束,则Oracle 则会自动在相应的约束列上建议唯一索引.数据库索引主要进行提高访问速度. 建设原则: 1.索引应该经常建在Where 子句经常用到的列上.如果某个大表经常使用某个字段进行查询,并且检索行数小于总表行数的5%.则应该考虑. 2.对于两表连接的字段,应该建立索引.如果经常在某表的一个字段进行Order By 则也经过进行索引. 3.不应该在小表上建设索引. 优缺点:

数据库、数据表建立索引的原则

数据库建立索引的原则 1,确定针对该表的操作是大量的查询操作还是大量的增删改操作. 2,尝试建立索引来帮助特定的查询.检查自己的sql语句,为那些频繁在where子句中出现的字段建立索引. 3,尝试建立复合索引来进一步提高系统性能.修改复合索引将消耗更长时间,同时,复合索引也占磁盘空间. 4,对于小型的表,建立索引可能会影响性能 5,应该避免对具有较少值的字段进行索引. 6,避免选择大型数据类型的列作为索引. 索引建立的原则 索引查询是数据库中重要的记录查询方法,要不要进入索引以及在那些字段上建

mongodb 建立索引提示异常:WiredTigerIndex::insert: key too large to index, failing 1483

{ "ok" : 0.0, "errmsg" : "WiredTigerIndex::insert: key too large to index, failing 1483 { : \"山东隔断|山东隔断厂家|山东隔断价格|山东活动隔断|山东酒店活动隔断|烟台活动玻璃隔断|山东活动展板|山东隔??...\" }", "code" : 17280 } MongoDB will not create an i