`

Lucene02---Lucene入门与Demo

    博客分类:
  • SEO
 
阅读更多

 

Lucene介绍:

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

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

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

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

 

 

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

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

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

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

    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:

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:xdwangiflytek@gmail.com
 */
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:

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:xdwangiflytek@gmail.com
 */
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.

 

 

创建的目录结构为:

 

 

 

运行结果:

 

 

 

 

  • 大小: 112.8 KB
  • 大小: 5.4 KB
  • 大小: 30.5 KB
6
0
分享到:
评论
1 楼 xler99 2014-07-29  
很好,谢谢啦啦~~~~~

相关推荐

    Lucene入门demo

    Lucene入门demo,lucene简单的应用

    luceneDemo(完整代码)

    luceneDemo(完整代码) lucene入门 基础类的运用、高亮器的实现、相关度排序

    lucene_demo例子

    可用lucene demo 已经有入门级pdf学习

    lucene3.0.0 入门DEMO

    lucene3.0.0 入门DEMO 适合新手使用 先要新建号相关的目录

    apache lucene 4.10.0入门单元测试代码demo

    总结了一些实用的demo 包括: 1.建立索引 2.通过IKAnalyzer搜索中文关键词 3.复杂的多字段搜索 4.多线程并发搜索,通过contiperf测试,详见:contiperf_百度百科 5.分页搜索 注意:lucene4.10.0需要jdk1.7以上...

    lucene入门demo

    里面编写了法创建,搜索的基本方法 LuceneDemo 单个文件索引,创建查找 CopyFile 为多文件复制多些文件做准备 CreateIndexe 多文件创建索引;Searcher多文件搜索对应CreateIndexe

    Lucenedemo

    lucene入门demo 实现基本的检索 可以进行改进

    Lucene快速入门

    Lucene是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎。Lucene以其方便使用、快速实施以及灵活性受到广泛的关注。它可以方便地嵌入到各种应用中实现针对应用的全文索引、检索功能,本总结使用lucene--...

    Lucene Demo

    Lucene使用的一个小Demo,有兴趣的可以下来看看,入门级

    lucene入门实例

    根据lucene demo 写的一个入门小例子,很小,希望对你有所帮助,不好别骂!

    Lucene3教程

    Lucene入门文档,包含索引的创建、查询、更新以及删除demo,各个常用类的详解

    harmonyos2-grails-hibernate-search-plugin:将HibernateSearch功能集成到Grails

    和声2 Grails Hibernate 搜索插件 这个插件旨在通过几个步骤将 ...~/.grails/${grailsVersion}/projects/${yourProjectName}/lucene-index/development/ 您可以在 application.yml 中覆盖此配置 hibern

    单点登录源码

    ├── zheng-demo-rpc-service -- rpc服务提供者 └── zheng-demo-web -- 演示示例[端口:8888] ``` ### 技术选型 #### 后端技术: 技术 | 名称 | 官网 ----|------|---- Spring Framework | 容器 | ...

    lucenc 工程实例

    初学lucene的同学可以参照一下,代码中整理了一些说明,可以很快入门lucene,希望对大家有用!

    AppProjects:存放一些Java,JavaEE,Android和iOS的二进制文件;里面同时有zip压缩文件,可以直接下载,不需要克隆整个仓库!!!都是一些小演示,注释详细一点,就不写教程文档了

    Android新控件ViewPager2入门示例 Android仿闲鱼底部导航栏 安卓阿里开源ARouterDemo Android使用RecyclerView播放视频列表 Android桌面图标和App名字 Android解决滑动冲突JavaEE JavaEE中Lucene入门程序 Struts2

    淘特站内搜索引擎(C#版)

    为了方便开发者快速入门索引接口的使用,我们制作了不同WEB开发语言(asp,jsp,php,.net)的索引接口开发事例,请参考demo目录中的相关文件。 索引接口开发完毕后,通过修改您原来的数据添加程序,在添加数据库后,...

    ZendFramework中文文档

    7.1. Zend_Controller 快速入门 7.1.1. 简介 7.1.2. 入门 7.1.2.1. 文件系统的组织结构 7.1.2.2. 设置文件根目录 7.1.2.3. 创建URL重写规则 7.1.2.4. 创建你的bootstrap文件 7.1.2.5. 创建默认的控制器...

Global site tag (gtag.js) - Google Analytics