`

compass如何实现文件搜索

阅读更多
把文件包装成对象
package fileSearcherTest;

import org.compass.annotations.Index;
import org.compass.annotations.Searchable;
import org.compass.annotations.SearchableId;
import org.compass.annotations.SearchableProperty;
import org.compass.annotations.Store;

@Searchable
public class TextFile {

	private String path;
	private String title;
	private String content;
	private long lastModified;

	@SearchableId
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	@SearchableProperty(boost=3.0f,index=Index.TOKENIZED,store=Store.YES)
	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
/*
 * 思考:content是否存储 ,如果文件很大存储会占用大量空间
 */
	@SearchableProperty(index=Index.TOKENIZED,store=Store.YES)
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}
	
	@SearchableProperty(index=Index.NO,store=Store.YES)
	public long getLastModified() {
		return lastModified;
	}

	public void setLastModified(long lastModified) {
		this.lastModified = lastModified;
	}

}



编写对文件的搜索类
package fileSearcherTest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import jeasy.analysis.MMAnalyzer;

import org.apache.lucene.analysis.Analyzer;
import org.compass.annotations.config.CompassAnnotationsConfiguration;
import org.compass.core.Compass;
import org.compass.core.CompassHighlighter;
import org.compass.core.CompassHits;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;

public class FileSearcher {

	private Compass compass;
	
	private Analyzer analyzer = new MMAnalyzer();

	public FileSearcher() {
		this.compass = new CompassAnnotationsConfiguration().setConnection(
				"./index").addClass(TextFile.class).setSetting(
				"compass.engine.highlighter.default.formatter.simple.pre",
				"<font color='red'>").setSetting(
				"compass.engine.highlighter.default.formatter.simple.post",
				"</font>").setSetting(
				"compass.engine.analyzer.default.type", analyzer)
				.buildCompass();
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				compass.close();
			}
		});
	}

	/*
	 * 给单个文件建索引 参数:字符串
	 */
	public void indexFile(String filePath) {
		File file = null;
		file = new File(filePath);
		indexFile(file);
	}

	/*
	 * 给单个文件建索引 参数:File
	 */
	public void indexFile(File file) {
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = null;
		/** ********解析Txt文件**************** */
		try {
			reader = new BufferedReader(new FileReader(file));
			for (;;) {
				String line = reader.readLine();
				if (line == null) {
					break;
				}
				sb.append(line).append("\n");
			}
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		/** *********包装成对象************* */
		TextFile tf = new TextFile();
		tf.setPath(file.getAbsolutePath());
		tf.setTitle(file.getName());
		tf.setContent(sb.toString());
		tf.setLastModified(file.lastModified());
		/** *********索引对象**************** */
		CompassSession session = null;
		CompassTransaction tx = null;
		try {
			session = compass.openSession();
			tx = session.beginLocalTransaction();
			session.create(tf);
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/*
	 * 给目录下的所有文件建索引
	 */
	public void index(File file) {
		if (file.isFile()) { // 如果是文件就建索引并保存
			indexFile(file);
			return;
		}
		File[] childs = file.listFiles();
		for (int i = 0; i < childs.length; i++) {
			File f = childs[i];
			if (f.isDirectory()) {// 如果是目录就递归调用
				index(f);
			} else {
				indexFile(f);
			}
		}
	}

	/*
	 * 给目录下的所有文件建索引
	 */
	public void index(String filePath) {
		File file = null;
		file = new File(filePath);
		index(file);
	}

	/*
	 * 删除索引 删除索引是根据索引的id来删除
	 */
	public void unIndex(File file) {
		TextFile tf = new TextFile();
		tf.setPath(file.getAbsolutePath());

		CompassSession session = null;
		CompassTransaction tx = null;
		try {
			session = compass.openSession();
			tx = session.beginLocalTransaction();
			session.delete(tf);
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/*
	 * 返回搜索的结果集 page_index:当前第几页 page_size:每页的大小
	 */
	public List<TextFile> search(String queryString, int page_index,
			int page_size) {
		CompassSession session = null;
		CompassTransaction tx = null;

		try {
			session = compass.openSession();
			tx = session.beginTransaction();
			CompassHits hits = session.find(queryString);
			int n = hits.length();
			if (n == 0) {
				return Collections.emptyList();
			}
			List<TextFile> tfs = new ArrayList<TextFile>(n);
			/** *********设置分页************** */
			int start_index = (page_index - 1) * page_size;
			int end_index = start_index + page_size;
			if (end_index > n) {
				end_index = n;
			}
			/** ************************ */
			CompassHighlighter highlighter = null;
			TextFile tf = null;
			for (int i = start_index; i < end_index; i++) {
				/** ********设置高亮器************* */
				highlighter = hits.highlighter(i);
				tf = (TextFile) hits.data(i);
				tf.setTitle(highlighter.fragment("title", tf.getTitle()));
				tf.setContent(highlighter.fragment("content", tf.getContent()));
				/** ************************** */
				tfs.add(tf);
			}
			hits.close();
			tx.commit();
			return tfs;
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

}


编写测试类man
package fileSearcherTest;

import java.util.List;

import org.junit.Test;

public class Man {

	private FileSearcher fileSearcher = new FileSearcher();
		
	@Test
	public  void testIndex() {
		//String dir = "E:\\EclipseStudyWorkspace\\Compass\\lucenceDataSource" ;
	    String dir = "E:\\EclipseStudyWorkspace\\Compass\\lucenceDataSource2" ;
	    
	    fileSearcher.index(dir) ;
	}
	@Test
	public  void testFileSearch() {
	    List<TextFile> tfs = fileSearcher.search("吴朝辉", 1, 100) ;
	    System.out.println("Results : "+tfs.size());
	    for(TextFile tf:tfs){
	    	System.out.println(tf.getPath());
	    	System.out.println("content:" +tf.getContent());
	    }
	}
		
}



这里测试的只是txt和doc文件  其他的文件爱你类型必须先做解析

分享到:
评论

相关推荐

    struts2+spring2.5+hibernate3.26+compass2.1搜索引擎简单实现(无jar包)

    在"struts2+spring2.5+hibernate3.26+compass2.1搜索引擎简单实现"这个项目中,首先你需要配置Struts2、Spring和Hibernate,确保它们能正常工作。这包括编写相应的配置文件(如struts.xml、spring-context.xml、...

    compass搜索引擎技术

    Compass搜索引擎技术是一种基于Lucene的全文检索框架,它提供了更高级别的API和集成机制,使得在Java应用程序中实现搜索引擎功能变得更加便捷。Compass的主要目标是将全文索引能力无缝地融入到现有的业务应用程序中...

    S2SH+compass (实现站内全文检索)

    标题中的"S2SH+compass"指的是一个基于Struts2(S),Spring(S)和Hibernate(H)这三种开源框架的Java Web应用,再加上Compass搜索引擎来实现站内全文检索的功能。这种组合常用于构建复杂的企业级应用,因为它提供...

    java搜索 compass资料

    这通常包括设置Compass的配置文件(如`compass.cfg.xml`),以及定义索引和搜索策略等。具体配置项取决于项目的需求,例如索引存储位置、索引更新频率等。 #### 五、Compass 高级特性 Compass 提供了许多高级特性...

    使用compass+lucene实现简单的全文检索功能

    2. **配置 Compass**:创建一个 Compass 配置文件,定义搜索引擎的连接参数,例如目录或数据库的位置,以及要索引的数据源。还可以设置分析器(Analyzer),用于处理文本数据。 3. **创建索引**:使用 Compass 提供...

    Spring ,JPA,Compass使用注解开发的博客站内搜索

    标题 "Spring ,JPA,Compass使用注解开发的博客站内搜索" 涉及的是在Java开发环境中,利用Spring框架、Java Persistence API (JPA) 和 Compass搜索引擎来实现一个博客系统的站内搜索功能。这是一项关键的技术,因为...

    Compass+SSH搜索引擎简单项目

    【SSH+Compass搜索引擎简单项目】是一个基于Struts2(S),Hibernate(H)和Spring(S)的Java Web应用程序,结合了Compass搜索引擎库,用于实现对数据库中两个表的高效检索功能。这个项目旨在提供一个清晰易懂的...

    compass完整可用项目

    Compass提供了一种简单的方式来在Java应用程序中集成全文搜索功能,使得开发者可以方便地在数据库、文件系统等存储中的对象上进行高效的全文检索。 Lucene是Apache软件基金会的开源项目,它是一个高性能、全文本...

    compass jar包

    Compass是一款开源的全文搜索引擎库,它为Java应用程序提供了强大的搜索功能。 Compass 2.1.0 版本是这个库的一个重要版本,它优化了...在实际应用中,应结合项目需求,充分挖掘Compass的功能,以实现最佳的搜索效果。

    Compass 的java代码

    6. **动态过滤器**:Compass允许你在运行时动态添加、修改和删除过滤器,以实现灵活的搜索条件控制。 7. **地理空间搜索**:Compass还支持地理空间搜索,可以对地理位置数据进行有效的检索。 **入门指南** 对于...

    SSH2整合compass做搜索引挚

    SSH2和Compass整合构建搜索引擎是一个在Java Web开发中实现高效全文检索的常见技术实践。SSH2是指Spring、Struts2和Hibernate这三个开源框架的组合,它们分别负责控制层、表现层和持久层的处理。而Compass是一个基于...

    Compass原理深入学习笔记

    【Compass原理深入学习笔记】 Compass是一款基于Apache Lucene的全文搜索引擎框架,它为...通过Compass,可以实现类似Hibernate对数据库的操作体验,但针对搜索引擎进行数据管理,提高了大规模文本数据的检索效率。

    compass-reference.pdf

    根据给定的文件信息,我们可以深入探讨Compass——一个强大的Java搜索引擎库,以及其核心概念、配置方式、连接管理、搜索引擎特性等关键知识点。 ### Compass概述 Compass是为Java开发人员设计的一个高性能、高...

    compass-2.2.0.zip

    Compass的出现就是为了降低这个门槛,使得开发人员可以更加专注于业务逻辑,而无需过多关注搜索引擎的实现细节。 Compass的核心特性包括: 1. **搜索引擎API**:Compass提供了一个简单易用的API,使得开发者可以...

    基于Luncene的compass框架详解-java

    通过以上步骤,我们可以在SSH架构的项目中无缝集成Compass框架,实现高效的全文搜索功能,提升应用程序的数据检索能力和用户体验。 总结而言,Compass框架通过其丰富的特性,如事物管理和快速更新优化,以及对...

    Compass技术文档

    - **OSEM**:OSEM (Object Search Engine Mapping) 是Compass提供的一个核心概念,它通过XML配置文件定义了如何将普通的Java对象(POJOs)映射到搜索引擎中。这极大地简化了对象与搜索引擎之间的交互过程。 #### 三...

    COMPASS介绍

    COMPASS是一个强大的搜索引擎框架,它通过OSEM(Object/Search Engine Mapping)技术实现了应用对象的领域模型与搜索引擎之间的映射。相较于其他搜索引擎框架如Hibernate Search,COMPASS在某些方面展现出了更高的...

    Compass与ssh框架整合

    通过以上步骤,我们可以将Compass与SSH框架成功整合,实现一个具备强大搜索功能的企业级应用。这不仅可以提高用户体验,也对后台数据管理带来便利,是现代Web开发中一项重要的技术实践。在实际项目中,开发者需要...

Global site tag (gtag.js) - Google Analytics