lucene的简单实例

本文介绍如何使用 Lucene 2.0 在 Windows 系统上为文本文件创建索引,并演示了如何进行简单查询。通过实例展示了索引构建过程及查询结果。

说明一下,这一篇文章的用到的lucene,是用2.0版本的,主要在查询的时候2.0版本的lucene与以前的版本有了一些区别.
其实这一些代码都是早几个月写的,自己很懒,所以到今天才写到自己的博客上,高深的文章自己写不了,只能记录下一些简单的记录与点滴,其中的代码算是自娱自乐的,希望高手不要把重构之类的砸下来...

1、在windows系统下的的C盘,建一个名叫s的文件夹,在该文件夹里面随便建三个txt文件,随便起名啦,就叫"1.txt","2.txt"和"3.txt"啦
其中1.txt的内容如下:

Java代码 复制代码
  1. 中华人民共和国   
  2. 全国人民   
  3. 2006 年  
中华人民共和国
全国人民
2006年


而"2.txt"和"3.txt"的内容也可以随便写几写,这里懒写,就复制一个和1.txt文件的内容一样吧

2、下载lucene包,放在classpath路径中
建立索引:

Java代码 复制代码
  1. package  lighter.javaeye.com;   
  2.   
  3. import  java.io.BufferedReader;   
  4. import  java.io.File;   
  5. import  java.io.FileInputStream;   
  6. import  java.io.IOException;   
  7. import  java.io.InputStreamReader;   
  8. import  java.util.Date;   
  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.index.IndexWriter;   
  15.   
  16. /**  
  17.  * author lighter date 2006-8-7  
  18.  */   
  19. public   class  TextFileIndexer {   
  20.      public   static   void  main(String[] args)  throws  Exception {   
  21.          /* 指明要索引文件夹的位置,这里是C盘的S文件夹下 */   
  22.         File fileDir =  new  File( "c://s" );   
  23.   
  24.          /* 这里放索引文件的位置 */   
  25.         File indexDir =  new  File( "c://index" );   
  26.         Analyzer luceneAnalyzer =  new  StandardAnalyzer();   
  27.         IndexWriter indexWriter =  new  IndexWriter(indexDir, luceneAnalyzer,   
  28.                  true );   
  29.         File[] textFiles = fileDir.listFiles();   
  30.          long  startTime =  new  Date().getTime();   
  31.            
  32.          //增加document到索引去   
  33.          for  ( int  i =  0 ; i < textFiles.length; i++) {   
  34.              if  (textFiles[i].isFile()   
  35.                     && textFiles[i].getName().endsWith( ".txt" )) {   
  36.                 System.out.println( "File "  + textFiles[i].getCanonicalPath()   
  37.                         +  "正在被索引...." );   
  38.                 String temp = FileReaderAll(textFiles[i].getCanonicalPath(),   
  39.                          "GBK" );   
  40.                 System.out.println(temp);   
  41.                 Document document =  new  Document();   
  42.                 Field FieldPath =  new  Field( "path" , textFiles[i].getPath(),   
  43.                         Field.Store.YES, Field.Index.NO);   
  44.                 Field FieldBody =  new  Field( "body" , temp, Field.Store.YES,   
  45.                         Field.Index.ANALYZED,   
  46.                         Field.TermVector.WITH_POSITIONS_OFFSETS);   
  47.                 document.add(FieldPath);   
  48.                 document.add(FieldBody);   
  49.                 indexWriter.addDocument(document);   
  50.             }   
  51.         }   
  52.          //optimize()方法是对索引进行优化   
  53.         indexWriter.optimize();   
  54.         indexWriter.close();   
  55.            
  56.          //测试一下索引的时间   
  57.          long  endTime =  new  Date().getTime();   
  58.         System.out   
  59.                 .println( "这花费了"   
  60.                         + (endTime - startTime)   
  61.                         +  " 毫秒来把文档增加到索引里面去!"   
  62.                         + fileDir.getPath());   
  63.     }   
  64.   
  65.      public   static  String FileReaderAll(String FileName, String charset)   
  66.              throws  IOException {   
  67.         BufferedReader reader =  new  BufferedReader( new  InputStreamReader(   
  68.                  new  FileInputStream(FileName), charset));   
  69.         String line =  new  String();   
  70.         String temp =  new  String();   
  71.            
  72.          while  ((line = reader.readLine()) !=  null ) {   
  73.             temp += line;   
  74.         }   
  75.         reader.close();   
  76.          return  temp;   
  77.     }   
  78. }  
package lighter.javaeye.com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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.index.IndexWriter;

/**
 * author lighter date 2006-8-7
 */
public class TextFileIndexer {
	public static void main(String[] args) throws Exception {
		/* 指明要索引文件夹的位置,这里是C盘的S文件夹下 */
		File fileDir = new File("c://s");

		/* 这里放索引文件的位置 */
		File indexDir = new File("c://index");
		Analyzer luceneAnalyzer = new StandardAnalyzer();
		IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer,
				true);
		File[] textFiles = fileDir.listFiles();
		long startTime = new Date().getTime();
		
		//增加document到索引去
		for (int i = 0; i < textFiles.length; i++) {
			if (textFiles[i].isFile()
					&& textFiles[i].getName().endsWith(".txt")) {
				System.out.println("File " + textFiles[i].getCanonicalPath()
						+ "正在被索引....");
				String temp = FileReaderAll(textFiles[i].getCanonicalPath(),
						"GBK");
				System.out.println(temp);
				Document document = new Document();
				Field FieldPath = new Field("path", textFiles[i].getPath(),
						Field.Store.YES, Field.Index.NO);
				Field FieldBody = new Field("body", temp, Field.Store.YES,
						Field.Index.TOKENIZED,
						Field.TermVector.WITH_POSITIONS_OFFSETS);
				document.add(FieldPath);
				document.add(FieldBody);
				indexWriter.addDocument(document);
			}
		}
		//optimize()方法是对索引进行优化
		indexWriter.optimize();
		indexWriter.close();
		
		//测试一下索引的时间
		long endTime = new Date().getTime();
		System.out
				.println("这花费了"
						+ (endTime - startTime)
						+ " 毫秒来把文档增加到索引里面去!"
						+ fileDir.getPath());
	}

	public static String FileReaderAll(String FileName, String charset)
			throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(FileName), charset));
		String line = new String();
		String temp = new String();
		
		while ((line = reader.readLine()) != null) {
			temp += line;
		}
		reader.close();
		return temp;
	}
}



索引的结果:

Java代码 复制代码
  1. File C:/s/ 1 .txt正在被索引....   
  2. 中华人民共和国全国人民 2006 年   
  3. File C:/s/ 2 .txt正在被索引....   
  4. 中华人民共和国全国人民 2006 年   
  5. File C:/s/ 3 .txt正在被索引....   
  6. 中华人民共和国全国人民 2006 年   
  7. 这花费了 297  毫秒来把文档增加到索引里面去!c:/s  
File C:/s/1.txt正在被索引....
中华人民共和国全国人民2006年
File C:/s/2.txt正在被索引....
中华人民共和国全国人民2006年
File C:/s/3.txt正在被索引....
中华人民共和国全国人民2006年
这花费了297 毫秒来把文档增加到索引里面去!c:/s



3、建立了索引之后,查询啦....

Java代码 复制代码
  1. package  lighter.javaeye.com;   
  2.   
  3. import  java.io.IOException;   
  4.   
  5. import  org.apache.lucene.analysis.Analyzer;   
  6. import  org.apache.lucene.analysis.standard.StandardAnalyzer;   
  7. import  org.apache.lucene.queryParser.ParseException;   
  8. import  org.apache.lucene.queryParser.QueryParser;   
  9. import  org.apache.lucene.search.Hits;   
  10. import  org.apache.lucene.search.IndexSearcher;   
  11. import  org.apache.lucene.search.Query;   
  12.   
  13. public   class  TestQuery {   
  14.      public   static   void  main(String[] args)  throws  IOException, ParseException {   
  15.         Hits hits =  null ;   
  16.         String queryString =  "中华" ;   
  17.         Query query =  null ;   
  18.         IndexSearcher searcher =  new  IndexSearcher( "c://index" );   
  19.   
  20.         Analyzer analyzer =  new  StandardAnalyzer();   
  21.          try  {   
  22.             QueryParser qp =  new  QueryParser( "body" , analyzer);   
  23.             query = qp.parse(queryString);   
  24.         }  catch  (ParseException e) {   
  25.         }   
  26.          if  (searcher !=  null ) {   
  27.             hits = searcher.search(query);   
  28.              if  (hits.length() >  0 ) {   
  29.                 System.out.println( "找到:"  + hits.length() +  " 个结果!" );   
  30.             }   
  31.         }   
  32.     }   
  33.   
  34. }  
package lighter.javaeye.com;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;

public class TestQuery {
	public static void main(String[] args) throws IOException, ParseException {
		Hits hits = null;
		String queryString = "中华";
		Query query = null;
		IndexSearcher searcher = new IndexSearcher("c://index");

		Analyzer analyzer = new StandardAnalyzer();
		try {
			QueryParser qp = new QueryParser("body", analyzer);
			query = qp.parse(queryString);
		} catch (ParseException e) {
		}
		if (searcher != null) {
			hits = searcher.search(query);
			if (hits.length() > 0) {
				System.out.println("找到:" + hits.length() + " 个结果!");
			}
		}
	}

}



其运行结果:

引用
找到:3 个结果!


具体的API的用法,这里就不说了,具体的做法参考lucene的官方文档吧...

MATLAB主动噪声和振动控制算法——对较大的次级路径变化具有鲁棒性内容概要:本文主要介绍了一种在MATLAB环境下实现的主动噪声和振动控制算法,该算法针对较大的次级路径变化具有较强的鲁棒性。文中详细阐述了算法的设计原理与实现方法,重点解决了传统控制系统中因次级路径动态变化导致性能下降的问题。通过引入自适应机制和鲁棒控制策略,提升了系统在复杂环境下的稳定性和控制精度,适用于需要高精度噪声与振动抑制的实际工程场景。此外,文档还列举了多个MATLAB仿真实例及相关科研技术服务内容,涵盖信号处理、智能优化、机器学习等多个交叉领域。; 适合人群:具备一定MATLAB编程基础和控制系统理论知识的科研人员及工程技术人员,尤其适合从事噪声与振动控制、信号处理、自动化等相关领域的研究生和工程师。; 使用场景及目标:①应用于汽车、航空航天、精密仪器等对噪声和振动敏感的工业领域;②用于提升现有主动控制系统对参数变化的适应能力;③为相关科研项目提供算法验证与仿真平台支持; 阅读建议:建议读者结合提供的MATLAB代码进行仿真实验,深入理解算法在不同次级路径条件下的响应特性,并可通过调整控制参数进一步探究其鲁棒性边界。同时可参考文档中列出的相关技术案例拓展应用场景。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值