Lucene介绍:

Lucene是一个高性能,可伸缩的全文检索工具包,可以使用他为你的应用程序添加索引和搜索能力。(注:它不是一个完整的搜索应用程序),Lucene目前是我们熟知的Apache里的一个开发项目,也是目前最为流行的基于Java开源全文检索工具包。

官网:http://lucene.apache.org/,从官网上看可以发现其版本不止Java的还有.NET等等。

目前已经有很多应用程序的搜索功能是基于Lucene的,例如我们用的Eclipse在第一次使用的时候,会有一个进度条,那就是创建索引的过程,方便Eclipse 的帮助系统的搜索功能。Lucene能够为文本类型的数据建立索引,所以你只要能把你要索引的数据格式转化为文本的,Lucene就能对你的文档进行索引和搜索。比如你要对一些HTML文档、PDF文档进行索引的话你就首先需要把HTML文档和PDF文档转换为文本格式的,然后将转换后的内容交给Lucene进行索引,然后再把创建好的索引文件保存到磁盘或内存中,最后根据用户输入的查询条件在索引文件上进行查询。

搜索应用程序和Lucene之间的关系:

Lucene02---Lucene入门与Demo

在用之前,我们再来对一些Lucene里的名字进行解释一下

IndexWriter: Lucene中最重要的的类之一,它主要是用来将文档加入索引,同时控制索引过程中的一些参数使用。操作索引库

Analyzer:分析器,主要用于分析搜索引擎遇到的各种文本。常用的有StandardAnalyzer分析器,StopAnalyzer分析器,WhitespaceAnalyzer分析器等。

Directory:索引存放的位置; Lucene提供了两种索引存放的位置,一种是磁盘,一种是内存。一般情况将索引放在磁盘上;相应地lucene提供了FSDirectory和RAMDirectory两个类。

Document:文档;Document相当于一个要进行索引的单元,任何可以想要被索引的文件都必须转化为Document对象才能进行索引。

Field:字段。

IndexSearcher:是Lucene中最基本的检索工具,所有的检索都会用到IndexSearcher工具;

Query:查询,Lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。

QueryParser: 是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象。

TopDocs:在搜索完成之后,需要把搜索结果返回并显示给用户,只有这样才算是完成搜索的目的。

Ok,废话就这么多,直接上代码。

FirstLucene

1、添加jar包

lucene-core-3.5.0.jar(核心)

lucene-analyzers-3.5.0.jar(分词器)

lucene-highlighter-3.5.0.jar(高亮器)

2、建立索引

3、 搜索

FirstLucene.java:

Java代码 Lucene02---Lucene入门与DemoLucene02---Lucene入门与DemoLucene02---Lucene入门与Demo
  1. packagecom.iflytek.lucene;
  2. importjava.io.File;
  3. importorg.apache.lucene.analysis.Analyzer;
  4. importorg.apache.lucene.analysis.standard.StandardAnalyzer;
  5. importorg.apache.lucene.document.Document;
  6. importorg.apache.lucene.index.IndexReader;
  7. importorg.apache.lucene.index.IndexWriter;
  8. importorg.apache.lucene.index.IndexWriterConfig;
  9. importorg.apache.lucene.queryParser.MultiFieldQueryParser;
  10. importorg.apache.lucene.queryParser.QueryParser;
  11. importorg.apache.lucene.search.Filter;
  12. importorg.apache.lucene.search.IndexSearcher;
  13. importorg.apache.lucene.search.Query;
  14. importorg.apache.lucene.search.ScoreDoc;
  15. importorg.apache.lucene.search.TopDocs;
  16. importorg.apache.lucene.store.Directory;
  17. importorg.apache.lucene.store.FSDirectory;
  18. importorg.apache.lucene.util.Version;
  19. /**
  20. *@authorxudongwang2012-2-2
  21. *
  22. *Email:[email protected]
  23. */
  24. publicclassFirstLucene{
  25. /**
  26. *源文件路径
  27. */
  28. privateStringfilePath01="F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneDatasource\\HelloLucene01.txt";
  29. privateStringfilePath02="F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneDatasource\\HelloLucene02.txt";
  30. privateStringfilePath03="F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneDatasource\\HelloLucene03.txt";
  31. /**
  32. *索引路径
  33. */
  34. privateStringindexPath="F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneIndex";
  35. /**
  36. *分词器,这里我们使用默认的分词器,标准分析器(好几个,但对中文的支持都不好)
  37. */
  38. privateAnalyzeranalyzer=newStandardAnalyzer(Version.LUCENE_35);
  39. /**
  40. *创建索引
  41. *
  42. *@throwsException
  43. */
  44. publicvoidcreateIndex()throwsException{
  45. Documentdocument01=File2Document.file2Document(filePath01);//要进行索引的单元
  46. Documentdocument02=File2Document.file2Document(filePath02);
  47. Documentdocument03=File2Document.file2Document(filePath03);
  48. //将Document添加到索引库中
  49. FileindexFile=newFile(indexPath);
  50. Directorydirectory=FSDirectory.open(indexFile);
  51. //IndexWriter是用来操作(增、删、改)索引库的
  52. //true,表示每次都创建新的,有了就删掉再创建
  53. IndexWriterConfigconf=newIndexWriterConfig(Version.LUCENE_35,
  54. analyzer);
  55. IndexWriterindexWriter=newIndexWriter(directory,conf);
  56. indexWriter.addDocument(document01);
  57. indexWriter.addDocument(document02);
  58. indexWriter.addDocument(document03);
  59. indexWriter.close();//涉及到资源的都需要释放
  60. }
  61. /**
  62. *搜索
  63. *
  64. *@paramqueryStr
  65. *搜索的关键词
  66. *@throwsException
  67. */
  68. publicvoidsearch(StringqueryStr)throwsException{
  69. //1、把要搜索的文本解析为Query对象
  70. //指定在哪些字段查询
  71. String[]fields={"name","content"};
  72. //QueryParser:是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象。
  73. QueryParserqueryParser=newMultiFieldQueryParser(Version.LUCENE_35,
  74. fields,analyzer);
  75. //Query:查询,lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。
  76. Queryquery=queryParser.parse(queryStr);
  77. //2、进行查询
  78. FileindexFile=newFile(indexPath);
  79. //IndexSearcher是用来在索引库中进行查询的
  80. //IndexSearcherindexSearcher=new
  81. //IndexSearcher(FSDirectory.open(indexFile));
  82. Directorydirectory=FSDirectory.open(indexFile);
  83. IndexReaderindexReader=IndexReader.open(directory);
  84. IndexSearcherindexSearcher=newIndexSearcher(indexReader);
  85. //Filter过滤器,我们可以将查出来的结果进行过滤,可以屏蔽掉一些不想给用户看到的内容
  86. Filterfilter=null;
  87. //10000表示一次性在数据库中查询多少个文档
  88. //topDocs类似集合
  89. TopDocstopDocs=indexSearcher.search(query,filter,10000);
  90. System.out.println("总共有【"+topDocs.totalHits+"】条匹配的结果");//注意这里的匹配结果是指文档的个数,而不是文档中包含搜索结果的个数
  91. //3、打印结果
  92. for(ScoreDocscoreDoc:topDocs.scoreDocs){
  93. intdocSn=scoreDoc.doc;//文档内部编号
  94. Documentdocument=indexSearcher.doc(docSn);//根据文档编号取出相应的文档
  95. File2Document.printDocumentInfo(document);//打印出文档信息
  96. }
  97. }
  98. publicstaticvoidmain(String[]args)throwsException{
  99. FirstLucenelucene=newFirstLucene();
  100. //lucene.createIndex();
  101. lucene.search("other");
  102. System.out.println("---------------------------");
  103. lucene.search("iteye");
  104. System.out.println("---------------------------");
  105. lucene.search("too");
  106. System.out.println("---------------------------");
  107. }
  108. }
package com.iflytek.lucene;import java.io.File;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.index.IndexReader;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriterConfig;import org.apache.lucene.queryParser.MultiFieldQueryParser;import org.apache.lucene.queryParser.QueryParser;import org.apache.lucene.search.Filter;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopDocs;import org.apache.lucene.store.Directory;import org.apache.lucene.store.FSDirectory;import org.apache.lucene.util.Version;/** * @author xudongwang 2012-2-2 *  *         Email:[email protected] */public class FirstLucene {	/**	 * 源文件路径	 */	private String filePath01 = "F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneDatasource\\HelloLucene01.txt";	private String filePath02 = "F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneDatasource\\HelloLucene02.txt";	private String filePath03 = "F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneDatasource\\HelloLucene03.txt";	/**	 * 索引路径	 */	private String indexPath = "F:\\Workspaces\\workspaceSE\\BlogDemo\\luceneIndex";	/**	 * 分词器,这里我们使用默认的分词器,标准分析器(好几个,但对中文的支持都不好)	 */	private Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);	/**	 * 创建索引	 * 	 * @throws Exception	 */	public void createIndex() throws Exception {		Document document01 = File2Document.file2Document(filePath01);// 要进行索引的单元		Document document02 = File2Document.file2Document(filePath02);		Document document03 = File2Document.file2Document(filePath03);		// 将Document添加到索引库中		File indexFile = new File(indexPath);		Directory directory = FSDirectory.open(indexFile);		// IndexWriter是用来操作(增、删、改)索引库的		// true,表示每次都创建新的,有了就删掉再创建		IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_35,				analyzer);		IndexWriter indexWriter = new IndexWriter(directory, conf);		indexWriter.addDocument(document01);		indexWriter.addDocument(document02);		indexWriter.addDocument(document03);		indexWriter.close();// 涉及到资源的都需要释放	}	/**	 * 搜索	 * 	 * @param queryStr	 *            搜索的关键词	 * @throws Exception	 */	public void search(String queryStr) throws Exception {		// 1、把要搜索的文本解析为Query对象		// 指定在哪些字段查询		String[] fields = { "name", "content" };		// QueryParser: 是一个解析用户输入的工具,可以通过扫描用户输入的字符串,生成Query对象。		QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_35,				fields, analyzer);		// Query:查询,lucene中支持模糊查询,语义查询,短语查询,组合查询等等,如有TermQuery,BooleanQuery,RangeQuery,WildcardQuery等一些类。		Query query = queryParser.parse(queryStr);		// 2、进行查询		File indexFile = new File(indexPath);		// IndexSearcher 是用来在索引库中进行查询的		// IndexSearcher indexSearcher = new		// IndexSearcher(FSDirectory.open(indexFile));		Directory directory = FSDirectory.open(indexFile);		IndexReader indexReader = IndexReader.open(directory);		IndexSearcher indexSearcher = new IndexSearcher(indexReader);		// Filter 过滤器,我们可以将查出来的结果进行过滤,可以屏蔽掉一些不想给用户看到的内容		Filter filter = null;		// 10000表示一次性在数据库中查询多少个文档		// topDocs 类似集合		TopDocs topDocs = indexSearcher.search(query, filter, 10000);		System.out.println("总共有【" + topDocs.totalHits + "】条匹配的结果");// 注意这里的匹配结果是指文档的个数,而不是文档中包含搜索结果的个数		// 3、打印结果		for (ScoreDoc scoreDoc : topDocs.scoreDocs) {			int docSn = scoreDoc.doc;// 文档内部编号			Document document = indexSearcher.doc(docSn);// 根据文档编号取出相应的文档			File2Document.printDocumentInfo(document);// 打印出文档信息		}	}	public static void main(String[] args) throws Exception {		FirstLucene lucene = new FirstLucene();		//lucene.createIndex();		lucene.search("other");		System.out.println("---------------------------");		lucene.search("iteye");		System.out.println("---------------------------");		lucene.search("too");		System.out.println("---------------------------");	}}

File2Document.java:

Java代码 Lucene02---Lucene入门与DemoLucene02---Lucene入门与DemoLucene02---Lucene入门与Demo
  1. packagecom.iflytek.lucene;
  2. importjava.io.BufferedReader;
  3. importjava.io.File;
  4. importjava.io.FileInputStream;
  5. importjava.io.FileNotFoundException;
  6. importjava.io.IOException;
  7. importjava.io.InputStreamReader;
  8. importorg.apache.lucene.document.Document;
  9. importorg.apache.lucene.document.Field;
  10. importorg.apache.lucene.document.Field.Index;
  11. importorg.apache.lucene.document.Field.Store;
  12. /**
  13. *@authorxudongwang2012-2-2
  14. *
  15. *Email:[email protected]
  16. */
  17. publicclassFile2Document{
  18. /**
  19. *File--->Document
  20. *
  21. *@paramfilePath
  22. *File路径
  23. *
  24. *@returnDocument对象
  25. */
  26. publicstaticDocumentfile2Document(StringfilePath){
  27. //文件要存放:name,content,size,path
  28. Filefile=newFile(filePath);
  29. Documentdocument=newDocument();
  30. //Store.YES是否存储yesnocompress(压缩之后再存)
  31. //Index是否进行索引Index.ANALYZED分词后进行索引,NOT_ANALYZED不索引,NOT_ANALYZED
  32. //不分词直接索引
  33. document.add(newField("name",file.getName(),Store.YES,
  34. Index.ANALYZED));
  35. document.add(newField("content",readFileContent(file),Store.YES,
  36. Index.ANALYZED));
  37. document.add(newField("size",String.valueOf(file.length()),
  38. Store.YES,Index.NOT_ANALYZED));//不分词,但是有时需要索引,文件大小(int)转换成String
  39. document.add(newField("path",file.getAbsolutePath(),Store.YES,
  40. Index.NOT_ANALYZED));//不需要根据文件的路径来查询
  41. returndocument;
  42. }
  43. /**
  44. *读取文件内容
  45. *
  46. *@paramfile
  47. *File对象
  48. *@returnFile的内容
  49. */
  50. privatestaticStringreadFileContent(Filefile){
  51. try{
  52. BufferedReaderreader=newBufferedReader(newInputStreamReader(
  53. newFileInputStream(file)));
  54. StringBuffercontent=newStringBuffer();
  55. try{
  56. for(Stringline=null;(line=reader.readLine())!=null;){
  57. content.append(line).append("\n");
  58. }
  59. }catch(IOExceptione){
  60. e.printStackTrace();
  61. }
  62. returncontent.toString();
  63. }catch(FileNotFoundExceptione){
  64. e.printStackTrace();
  65. }
  66. returnnull;
  67. }
  68. /**
  69. *<pre>
  70. *获取name属性值的两种方法
  71. *1.Filedfield=document.getFiled("name");
  72. *field.stringValue();
  73. *2.document.get("name");
  74. *</pre>
  75. *
  76. *@paramdocument
  77. */
  78. publicstaticvoidprintDocumentInfo(Documentdocument){
  79. //TODOAuto-generatedmethodstub
  80. System.out.println("name-->"+document.get("name"));
  81. System.out.println("content-->"+document.get("content"));
  82. System.out.println("path-->"+document.get("path"));
  83. System.out.println("size-->"+document.get("size"));
  84. }
  85. }
package com.iflytek.lucene;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.Field.Index;import org.apache.lucene.document.Field.Store;/** * @author xudongwang 2012-2-2 *  *         Email:[email protected] */public class File2Document {	/**	 * File--->Document	 * 	 * @param filePath	 *            File路径	 * 	 * @return Document对象	 */	public static Document file2Document(String filePath) {		// 文件要存放:name,content,size,path		File file = new File(filePath);		Document document = new Document();		// Store.YES 是否存储 yes no compress(压缩之后再存)		// Index 是否进行索引 Index.ANALYZED 分词后进行索引,NOT_ANALYZED 不索引,NOT_ANALYZED		// 不分词直接索引		document.add(new Field("name", file.getName(), Store.YES,				Index.ANALYZED));		document.add(new Field("content", readFileContent(file), Store.YES,				Index.ANALYZED));		document.add(new Field("size", String.valueOf(file.length()),				Store.YES, Index.NOT_ANALYZED));// 不分词,但是有时需要索引,文件大小(int)转换成String		document.add(new Field("path", file.getAbsolutePath(), Store.YES,				Index.NOT_ANALYZED));// 不需要根据文件的路径来查询		return document;	}	/**	 * 读取文件内容	 * 	 * @param file	 *            File对象	 * @return File的内容	 */	private static String readFileContent(File file) {		try {			BufferedReader reader = new BufferedReader(new InputStreamReader(					new FileInputStream(file)));			StringBuffer content = new StringBuffer();			try {				for (String line = null; (line = reader.readLine()) != null;) {					content.append(line).append("\n");				}			} catch (IOException e) {				e.printStackTrace();			}			return content.toString();		} catch (FileNotFoundException e) {			e.printStackTrace();		}		return null;	}	/**	 * <pre>	 * 获取name属性值的两种方法  	 * 1.Filed field = document.getFiled("name");  	 *         field.stringValue();  	 * 2.document.get("name");	 * </pre>	 * 	 * @param document	 */	public static void printDocumentInfo(Document document) {		// TODO Auto-generated method stub		System.out.println("name -->" + document.get("name"));		System.out.println("content -->" + document.get("content"));		System.out.println("path -->" + document.get("path"));		System.out.println("size -->" + document.get("size"));	}}

HelloLucene01.txt:

Hello, my name is wang xudong, I in iteye blog address is xdwangiflytek.iteye.com.

HelloLucene02.txt:

Hello, my name is wang xudong, I in iteye blog address is xdwangiflytek.iteye.com too.

HelloLucene03.txt:

iteye too other.

创建的目录结构为:

Lucene02---Lucene入门与Demo

运行结果:

Lucene02---Lucene入门与Demo

相关文章:

  • 2021-09-09
  • 2021-07-30
  • 2021-06-14
  • 2021-04-19
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-09
  • 2022-01-14
相关资源
相似解决方案