`

compass如何实现对对象的增删改查操作 设置高亮器 索引分页

阅读更多
编写要索引的类
Book
package objectSearcherTest;

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 Book {
    
	private String id ;
	private String title ;
	private String author ;
	private float price ;
	
	public Book(){}

	public Book(String id, String title, String author, float price) {
		super();
		this.id = id;
		this.title = title;
		this.author = author;
		this.price = price;
	}

	@SearchableId
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

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

	public void setTitle(String title) {
		this.title = title;
	}

	@SearchableProperty(index=Index.ANALYZED,store=Store.YES)
	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	@SearchableProperty(index=Index.NOT_ANALYZED,store=Store.YES)
	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	@Override
	public String toString() {
		
		return "[id:"+id+"  title:"+title+"  author:"+author+"  price:"+price+"]" ;
	}
}


seacher
/**
 * 知识点补充
 * 如果不是使用compass,而是lucene,关于IndexSearcher需要注意的两点
 * 一 :一旦打开不会搜索到以后添加的索引(因为有内部状态)
 * 二 :是线程安全的,多个线程仅需一个实例
 * 思考:IndexSearcher是不能以成员变量的形式出现在类中,只能需要它的时候new个新的
 * 带来的后果:在web应用中会有很多个IndexSearcher实例
 * 解决方案:动态检测索引有没有被修改过,只要没有被修改就无需new一个新的IndexSearcher,
 * 
 * IndexWriter需注意的几点:
 * 一 :修改索引后,需要用flush()或close()方能使索引失效
 * 二 :非线程安全,在任意时候仅有一个线程对其操作
 * 三 :lucene不负责线程同步,同步问题交由应用程序自己解决
 * 
 * 对多线程优化lucene的几种策略:
 * 一 :使用ReadWriteLock
 * 二 :使用Version Check
 * 三 :开发泛型安全的 FrameWork Searcher
 */
package objectSearcherTest;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
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 Searcher {
	private Compass compass;

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

	/*
	 * 给对象建索引
	 */
	public void index(Book book) {
		CompassSession session = null;
		CompassTransaction tx = null;
		try {
			session = compass.openSession();
			tx = session.beginLocalTransaction();
			session.create(book);
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/*
	 * 删除索引
	 */
	public void unIndex(Book book) {
		CompassSession session = null;
		CompassTransaction tx = null;
		try {
			session = compass.openSession();
			tx = session.beginLocalTransaction();
			session.delete(book);
			tx.commit();
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	/*
	 * 重建索引
	 */
	public void reIndex(Book book) {
		unIndex(book);
		index(book);
	}

	/*
	 * 返回搜索的结果集 page_index:当前第几页 page_size:每页的大小
	 */
	public List<Book> 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);
			/** **替代find的强大的CopassQueryBuilder**** */
			/*
			 * //以下供参考 CompassQueryBuilder builder = session.queryBuilder() ;
			 * System.out.println("Book.class.getSimpleName() = "
			 * +Book.class.getSimpleName()); CompassQuery query1 =
			 * builder.alias(Book.class.getSimpleName()) ; CompassQuery query2 =
			 * builder.queryString(queryString).toQuery() ;
			 * CompassBooleanQueryBuilder bb = builder.bool() ; CompassQuery
			 * query = bb.addMust(query1).addMust(query2).toQuery(); CompassHits
			 * hits2 = query.hits() ;
			 */
			/** *************************************** */
			int n = hits.length();
			if (n == 0) {
				return Collections.emptyList();
			}
			List<Book> books = new ArrayList<Book>(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;
			Book book = null;
			for (int i = start_index; i < end_index; i++) {
				/** ********设置高亮器************* */
				highlighter = hits.highlighter(i);
				book = (Book) hits.data(i);
				book.setTitle(highlighter.fragment("title", book.getTitle()));
				/** ************************** */
				books.add(book);
			}
			hits.close();
			tx.commit();
			return books;
		} catch (RuntimeException e) {
			tx.rollback();
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
}



测试类man
package objectSearcherTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.junit.Test;

public class Man {

	 List<Book> db = new ArrayList<Book>() ;//模拟数据库存储
	 Searcher searcher = new Searcher("./index");
	
	@Test
	public  void testman() {
		add(new Book(UUID.randomUUID().toString(),"Thinking in java","Bruce",10.9f));
		add(new Book(UUID.randomUUID().toString(),"Effective java","Joshua",10.9f));
		add(new Book(UUID.randomUUID().toString(),"Java Thread Programming","Paul",10.9f));
		int n ;
		do{
			n = displaySelection();
			switch(n){
			case 1:
				System.out.println("========");
				listBooks();
				System.out.println("---------");
				break ;
			case 2:
				addBook();
				break ;
			case 3:
				deleteBook();
				break ;
			case 4:
				searchBook() ;
				break ;
			case 5:
				return ;
			default:
				System.out.println("\n您的输入有错请重新输入(1~5):\n");
			    break;
			}
		}while(n!=0);
		 

	}
	public  void searchBook() {
		String q = readLine("Enter keywords: ") ;
		List<Book> books = searcher.search(q,1,10) ;
		System.out.println("== search results: "+books.size()+" ==");
		for(Book book:books){
			System.out.println(book);
		}
		
	}

	public void addBook() {
		String title = readLine("Title:");
		String author = readLine("Author:");
		String price = readLine("Price:");
		Book book = new Book(UUID.randomUUID().toString(),title,author,Float.valueOf(price));
		add(book);
	}


	public String readLine(String prompt) {
		System.out.println(prompt);
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		
		try {
			return reader.readLine() ;
		} catch (Exception e) {
			throw  new RuntimeException(e);
		}
	}


	public  void listBooks() {
	 System.out.println("== Database ==");
		int n = 1 ;
		for(Book book :db){
			System.out.println(n+" | " + book);
			n++ ;
		}
		
	}


	public  int displaySelection() {
		System.out.println("\n== Select ==");
		System.out.println("1. List all books");
		System.out.println("2. Add new book");
		System.out.println("3. Delete book");
		System.out.println("4. Search book");
		System.out.println("5. Exit");
		int n = readKey() ;
		if(n>=1 && n<=5){
			//System.out.println("n = " + n);
			return n ;
		}
		return n;
	}


	public void add(Book book) {
		db.add(book) ;
		searcher.index(book) ;
		
	}
	public void deleteBook() {
              listBooks();
              System.out.println("Book index :");
             int n = readKey();
		     Book book = db.remove(n-1) ;
		     searcher.unIndex(book) ;
	}
	public  int readKey() {
		BufferedReader reader = null ;
		 int n;
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			 String str = reader.readLine();
			 n = Integer.valueOf(str.trim()) ;
			//System.out.println("readKey = " + n);
			return n ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	   return 1 ;
	}

}


该程序是模拟数据库的操作
测试结果如下

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
1
========
== Database ==
1 | [id:9db5641b-957d-436e-94a1-5b4d7faaf028  title:Thinking in java  author:Bruce  price:10.9]
2 | [id:852ff241-62ee-4d94-9604-12b7db390edb  title:Effective java  author:Joshua  price:10.9]
3 | [id:3979a6aa-68b2-4668-b4c0-551799e1806b  title:Java Thread Programming  author:Paul  price:10.9]
---------

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
2
Title:
java
Author:
wuzhaohui
Price:
100.0

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
1
========
== Database ==
1 | [id:9db5641b-957d-436e-94a1-5b4d7faaf028  title:Thinking in java  author:Bruce  price:10.9]
2 | [id:852ff241-62ee-4d94-9604-12b7db390edb  title:Effective java  author:Joshua  price:10.9]
3 | [id:3979a6aa-68b2-4668-b4c0-551799e1806b  title:Java Thread Programming  author:Paul  price:10.9]
4 | [id:ae3c2b3e-2d66-4c4a-8e59-7758071e7a2c  title:java  author:wuzhaohui  price:100.0]
---------

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
3
== Database ==
1 | [id:9db5641b-957d-436e-94a1-5b4d7faaf028  title:Thinking in java  author:Bruce  price:10.9]
2 | [id:852ff241-62ee-4d94-9604-12b7db390edb  title:Effective java  author:Joshua  price:10.9]
3 | [id:3979a6aa-68b2-4668-b4c0-551799e1806b  title:Java Thread Programming  author:Paul  price:10.9]
4 | [id:ae3c2b3e-2d66-4c4a-8e59-7758071e7a2c  title:java  author:wuzhaohui  price:100.0]
Book index :
4

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
1
========
== Database ==
1 | [id:9db5641b-957d-436e-94a1-5b4d7faaf028  title:Thinking in java  author:Bruce  price:10.9]
2 | [id:852ff241-62ee-4d94-9604-12b7db390edb  title:Effective java  author:Joshua  price:10.9]
3 | [id:3979a6aa-68b2-4668-b4c0-551799e1806b  title:Java Thread Programming  author:Paul  price:10.9]
---------

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
4
Enter keywords:
java
== search results: 10 ==
[id:d954cce3-dd51-44b0-90a1-3363239d9559  title:Thinking in <font color='red'>java</font>  author:Bruce  price:0.0]
[id:903b8b04-d57a-4203-8464-f008bb8c3896  title:Effective <font color='red'>java</font>  author:Joshua  price:0.0]
[id:e82301b5-1583-478d-893f-5b8b078364a5  title:<font color='red'>Java</font> Thread Programming  author:Paul  price:0.0]
[id:9db5641b-957d-436e-94a1-5b4d7faaf028  title:Thinking in <font color='red'>java</font>  author:Bruce  price:0.0]
[id:852ff241-62ee-4d94-9604-12b7db390edb  title:Effective <font color='red'>java</font>  author:Joshua  price:0.0]
[id:3979a6aa-68b2-4668-b4c0-551799e1806b  title:<font color='red'>Java</font> Thread Programming  author:Paul  price:0.0]
[id:6ee2c10e-dde0-448b-8ca9-9e66cdeedc14  title:Thinking in <font color='red'>java</font>  author:Bruce  price:0.0]
[id:25e861b1-eff5-4eb9-8d5e-191131e968e8  title:Effective <font color='red'>java</font>  author:Joshua  price:0.0]
[id:6ec4f321-67b2-460b-b416-eb9d2cecae6d  title:Thinking in <font color='red'>java</font>  author:Bruce  price:0.0]
[id:0d5ebf4a-0ef6-4475-9872-db9015637381  title:Effective <font color='red'>java</font>  author:Joshua  price:0.0]

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
3
== Database ==
1 | [id:9db5641b-957d-436e-94a1-5b4d7faaf028  title:Thinking in java  author:Bruce  price:10.9]
2 | [id:852ff241-62ee-4d94-9604-12b7db390edb  title:Effective java  author:Joshua  price:10.9]
3 | [id:3979a6aa-68b2-4668-b4c0-551799e1806b  title:Java Thread Programming  author:Paul  price:10.9]
Book index :
3

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit
1
========
== Database ==
1 | [id:9db5641b-957d-436e-94a1-5b4d7faaf028  title:Thinking in java  author:Bruce  price:10.9]
2 | [id:852ff241-62ee-4d94-9604-12b7db390edb  title:Effective java  author:Joshua  price:10.9]
---------

== Select ==
1. List all books
2. Add new book
3. Delete book
4. Search book
5. Exit



1
0
分享到:
评论

相关推荐

    巴巴运动网-产品搜索

    在巴巴运动网的产品搜索功能中,黎活明老师介绍了如何利用Compass的注解(@Searchable、@SearchableId、@SearchableProperty等)来实现对产品信息的索引和检索。 2. **Compass配置与使用**:通过设置Compass的连接...

    JAVA上百实例源码以及开源项目源代码

    Java数组倒置 简单 Java图片加水印,支持旋转和透明度设置 摘要:Java源码,文件操作,图片水印 util实现Java图片水印添加功能,有添加图片水印和文字水印,可以设置水印位置,透明度、设置对线段锯齿状边缘处理、水印...

    java开源包3

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包4

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包1

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包11

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包2

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包6

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包5

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包10

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包8

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包7

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包9

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    java开源包101

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

    Java资源包01

    利用JoSQL可以像操作数据库中的数据一样对任何Java对象集进行查询,排序,分组。 搜索自动提示 Autotips AutoTips是为解决应用系统对于【自动提示】的需要(如:Google搜索), 而开发的架构无关的公共控件, 以满足该类...

Global site tag (gtag.js) - Google Analytics