Compass入门指南(二)

Compass框架的参考文档,Compass是在Lucene的基础上做了封装,支持索引事务控制和增量索引,同时也能够和主流的SSH框架完美地整合在一起,操作Compass类似于操作Hibernate,它们的类/方法等设计的非常相似。下面我们通过一个实例来看看Compass到底是怎样来索引数据库,操作索引库和实现搜索功能的。
    步骤一:下载Compass,目前最新版本是2.2.0,可以到http://www.compass-project.org/上下载。
    步骤二:在Eclipse中新建一个Java Project,解压compass-2.2.0-with-dependencies.zip,将dist目录下的compass-2.2.0.jar,commons-logging.jar和dist/lucene目录下的lucene-analyzers.jar,lucene-core.jar,lucene-highlighter.jar拷贝在工程的构建路径下. 
    步骤三:新建一个Book(书籍)类,这个类就是我们要搜索的对象,其完整代码如下:

Java代码 复制代码
  1.   
  2. import org.compass.annotations.Index;   
  3. import org.compass.annotations.Searchable;   
  4. import org.compass.annotations.SearchableId;   
  5. import org.compass.annotations.SearchableProperty;   
  6. import org.compass.annotations.Store;   
  7.   
  8. @Searchable  
  9. public class Book {   
  10.     private String id;//编号   
  11.     private String title;//标题   
  12.     private String author;//作者   
  13.     private float price;//价格   
  14.   
  15.     public Book() {   
  16.     }   
  17.   
  18.     public Book(String id, String title, String author, float price) {   
  19.         super();   
  20.         this.id = id;   
  21.         this.title = title;   
  22.         this.author = author;   
  23.         this.price = price;   
  24.     }   
  25.   
  26.     @SearchableId  
  27.     public String getId() {   
  28.         return id;   
  29.     }   
  30.   
  31.     @SearchableProperty(boost = 2.0F, index = Index.TOKENIZED, store = Store.YES)   
  32.     public String getTitle() {   
  33.         return title;   
  34.     }   
  35.   
  36.     @SearchableProperty(index = Index.TOKENIZED, store = Store.YES)   
  37.     public String getAuthor() {   
  38.         return author;   
  39.     }   
  40.   
  41.     @SearchableProperty(index = Index.NO, store = Store.YES)   
  42.     public float getPrice() {   
  43.         return price;   
  44.     }   
  45.   
  46.     public void setId(String id) {   
  47.         this.id = id;   
  48.     }   
  49.   
  50.     public void setTitle(String title) {   
  51.         this.title = title;   
  52.     }   
  53.   
  54.     public void setAuthor(String author) {   
  55.         this.author = author;   
  56.     }   
  57.   
  58.     public void setPrice(float price) {   
  59.         this.price = price;   
  60.     }   
  61.   
  62.     @Override  
  63.     public String toString() {   
  64.         return "[" + id + "] " + title + " - " + author + " $ " + price;   
  65.     }   
  66.   
  67. }  
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;
	}

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

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

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

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

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

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

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

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

}


    这里有几个要注意的地方:@Searchable表示该类的对象是可被搜索的;@SearchableId表示索引建立的id;@SearchableProperty表示此字段可以被索引、被检索;对于Index,Store在这里就不作介绍了,不熟悉的朋友可以去看看Lucene API。
    步骤四:新建一个Searcher类,该类封装了对索引库的一些操作,包括新建索引,删除索引,重建索引,搜索等等。完整代码如下:

Java代码 复制代码
  1. import java.util.ArrayList;   
  2. import java.util.Collections;   
  3. import java.util.List;   
  4.   
  5. import org.compass.annotations.config.CompassAnnotationsConfiguration;   
  6. import org.compass.core.Compass;   
  7. import org.compass.core.CompassHits;   
  8. import org.compass.core.CompassSession;   
  9. import org.compass.core.CompassTransaction;   
  10.   
  11. public class Searcher   
  12. {   
  13.     protected Compass compass;   
  14.   
  15.     public Searcher()   
  16.     {   
  17.     }   
  18.   
  19.     /**  
  20.      * 初始化Compass  
  21.      * @param path  
  22.      */  
  23.     public Searcher(String path)   
  24.     {   
  25.         compass = new CompassAnnotationsConfiguration().setConnection(path).addClass(Book.class).setSetting("compass.engine.highlighter.default.formatter.simple.pre""<font color='red'>").setSetting(   
  26.                 "compass.engine.highlighter.default.formatter.simple.post""</font>").buildCompass();   
  27.         Runtime.getRuntime().addShutdownHook(new Thread()   
  28.         {   
  29.             public void run()   
  30.             {   
  31.                 compass.close();   
  32.             }   
  33.         });   
  34.   
  35.     }   
  36.   
  37.     /**  
  38.      * 新建索引  
  39.      * @param book  
  40.      */  
  41.     public void index(Book book)   
  42.     {   
  43.         CompassSession session = null;   
  44.         CompassTransaction tx = null;   
  45.         try  
  46.         {   
  47.             session = compass.openSession();   
  48.             tx = session.beginTransaction();   
  49.             session.create(book);   
  50.             tx.commit();   
  51.         } catch (RuntimeException e)   
  52.         {   
  53.             if(tx!=null)   
  54.                 tx.rollback();   
  55.             throw e;   
  56.         } finally  
  57.         {   
  58.             if (session != null)   
  59.             {   
  60.                 session.close();   
  61.             }   
  62.         }   
  63.     }   
  64.   
  65.     /**  
  66.      * 删除索引  
  67.      * @param book  
  68.      */  
  69.     public void unIndex(Book book)   
  70.     {   
  71.         CompassSession session = null;   
  72.         CompassTransaction tx = null;   
  73.         try  
  74.         {   
  75.             session = compass.openSession();   
  76.             tx = session.beginTransaction();   
  77.             session.delete(book);   
  78.             tx.commit();   
  79.         } catch (RuntimeException e)   
  80.         {   
  81.             tx.rollback();   
  82.             throw e;   
  83.         } finally  
  84.         {   
  85.             if (session != null)   
  86.             {   
  87.                 session.close();   
  88.             }   
  89.         }   
  90.     }   
  91.   
  92.     /**  
  93.      * 重建索引  
  94.      * @param book  
  95.      */  
  96.     public void reIndex(Book book)   
  97.     {   
  98.         unIndex(book);   
  99.         index(book);   
  100.     }   
  101.   
  102.     /**  
  103.      * 搜索  
  104.      * @param queryString  
  105.      * @return  
  106.      */  
  107.     public List<Book> search(String queryString)   
  108.     {   
  109.         CompassSession session = null;   
  110.         CompassTransaction tx = null;   
  111.         try  
  112.         {   
  113.             session = compass.openSession();   
  114.             tx = session.beginTransaction();   
  115.             CompassHits hits = session.find(queryString);   
  116.             int n = hits.length();   
  117.             if (0 == n)   
  118.             {   
  119.                 return Collections.emptyList();   
  120.             }   
  121.             List<Book> books = new ArrayList<Book>();   
  122.             for (int i = 0; i < n; i++)   
  123.             {   
  124.                 books.add((Book) hits.data(i));   
  125.             }   
  126.             hits.close();   
  127.             tx.commit();   
  128.             return books;   
  129.         } catch (RuntimeException e)   
  130.         {   
  131.             tx.rollback();   
  132.             throw e;   
  133.         } finally  
  134.         {   
  135.             if (session != null)   
  136.             {   
  137.                 session.close();   
  138.             }   
  139.         }   
  140.     }   
  141. }  
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.CompassHits;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;

public class Searcher
{
	protected Compass compass;

	public Searcher()
	{
	}

	/**
	 * 初始化Compass
	 * @param path
	 */
	public Searcher(String path)
	{
		compass = new CompassAnnotationsConfiguration().setConnection(path).addClass(Book.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();
			}
		});

	}

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

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

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

	/**
	 * 搜索
	 * @param queryString
	 * @return
	 */
	public List<Book> search(String queryString)
	{
		CompassSession session = null;
		CompassTransaction tx = null;
		try
		{
			session = compass.openSession();
			tx = session.beginTransaction();
			CompassHits hits = session.find(queryString);
			int n = hits.length();
			if (0 == n)
			{
				return Collections.emptyList();
			}
			List<Book> books = new ArrayList<Book>();
			for (int i = 0; i < n; i++)
			{
				books.add((Book) hits.data(i));
			}
			hits.close();
			tx.commit();
			return books;
		} catch (RuntimeException e)
		{
			tx.rollback();
			throw e;
		} finally
		{
			if (session != null)
			{
				session.close();
			}
		}
	}
}


    步骤五:新建一个测试类进行测试.完整源码如下:

Java代码 复制代码
  1. import java.io.BufferedReader;   
  2. import java.io.InputStreamReader;   
  3. import java.util.ArrayList;   
  4. import java.util.List;   
  5. import java.util.UUID;   
  6.   
  7. public class Main   
  8. {   
  9.     static List<Book> db = new ArrayList<Book>();   
  10.     static Searcher searcher = new Searcher("E:/index");   
  11.   
  12.     public static void main(String[] args)   
  13.     {   
  14.         add(new Book(UUID.randomUUID().toString(), "Thinking in Java""Bruce"109.0f));   
  15.         add(new Book(UUID.randomUUID().toString(), "Effective Java""Joshua"12.4f));   
  16.         add(new Book(UUID.randomUUID().toString(), "Java Thread Programing""Paul"25.8f));   
  17.         int n;   
  18.         do  
  19.         {   
  20.             n = displaySelection();   
  21.             switch (n)   
  22.             {   
  23.             case 1:   
  24.                 listBooks();   
  25.                 break;   
  26.             case 2:   
  27.                 addBook();   
  28.                 break;   
  29.             case 3:   
  30.                 deleteBook();   
  31.                 break;   
  32.             case 4:   
  33.                 searchBook();   
  34.                 break;   
  35.             case 5:   
  36.                 return;   
  37.             }   
  38.         } while (n != 0);   
  39.     }   
  40.   
  41.     static int displaySelection()   
  42.     {   
  43.         System.out.println("/n==select==");   
  44.         System.out.println("1. List all books");   
  45.         System.out.println("2. Add book");   
  46.         System.out.println("3. Delete book");   
  47.         System.out.println("4. Search book");   
  48.         System.out.println("5. Exit");   
  49.         int n = readKey();   
  50.         if (n >= 1 && n <= 5)   
  51.             return n;   
  52.         return 0;   
  53.     }   
  54.   
  55.     /**  
  56.      * 增加一本书到数据库和索引中  
  57.      * @param book  
  58.      */  
  59.     private static void add(Book book)   
  60.     {   
  61.         db.add(book);   
  62.         searcher.index(book);   
  63.     }   
  64.   
  65.     /**  
  66.      * 打印出数据库中的所有书籍列表  
  67.      */  
  68.     public static void listBooks()   
  69.     {   
  70.         System.out.println("==Database==");   
  71.         int n =1;   
  72.         for (Book book :db)   
  73.         {   
  74.             System.out.println(n+")"+book);   
  75.             n++;   
  76.         }   
  77.     }   
  78.   
  79.     /**  
  80.      * 根据用户录入,增加一本书到数据库和索引中  
  81.      */  
  82.     public static void addBook()   
  83.     {   
  84.         String title = readLine(" Title: ");   
  85.         String author = readLine(" Author: ");   
  86.         String price = readLine(" Price: ");   
  87.         Book book = new Book(UUID.randomUUID().toString(),title,author,Float.valueOf(price));   
  88.         add(book);   
  89.     }   
  90.   
  91.     /**  
  92.      * 删除一本书,同时删除数据库,索引库中的  
  93.      */  
  94.     public static void deleteBook()   
  95.     {   
  96.         listBooks();   
  97.         System.out.println("Book index: ");   
  98.         int n = readKey();   
  99.         Book book = db.remove(n-1);   
  100.         searcher.unIndex(book);   
  101.     }   
  102.   
  103.     /**  
  104.      * 根据输入的关键字搜索书籍  
  105.      */  
  106.     public static void searchBook()   
  107.     {   
  108.         String queryString = readLine(" Enter keyword: ");   
  109.         List<Book> books = searcher.search(queryString);   
  110.         System.out.println(" ====search results:"+books.size()+"====");   
  111.         for (Book book :books)   
  112.         {   
  113.             System.out.println(book);   
  114.         }   
  115.     }   
  116.   
  117.     public static int readKey()   
  118.     {   
  119.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));   
  120.         try  
  121.         {   
  122.             int n = reader.read();   
  123.             n=Integer.parseInt(Character.toString((char)n));   
  124.             return n;   
  125.         }catch(Exception e)   
  126.         {   
  127.             throw new RuntimeException();   
  128.         }   
  129.     }   
  130.        
  131.     public static String readLine(String propt)   
  132.     {   
  133.         System.out.println(propt);   
  134.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));   
  135.         try{   
  136.             return reader.readLine();   
  137.         }catch(Exception e)   
  138.         {   
  139.             throw new RuntimeException();   
  140.         }   
  141.     }   
  142. }  
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class Main
{
	static List<Book> db = new ArrayList<Book>();
	static Searcher searcher = new Searcher("E:/index");

	public static void main(String[] args)
	{
		add(new Book(UUID.randomUUID().toString(), "Thinking in Java", "Bruce", 109.0f));
		add(new Book(UUID.randomUUID().toString(), "Effective Java", "Joshua", 12.4f));
		add(new Book(UUID.randomUUID().toString(), "Java Thread Programing", "Paul", 25.8f));
		int n;
		do
		{
			n = displaySelection();
			switch (n)
			{
			case 1:
				listBooks();
				break;
			case 2:
				addBook();
				break;
			case 3:
				deleteBook();
				break;
			case 4:
				searchBook();
				break;
			case 5:
				return;
			}
		} while (n != 0);
	}

	static int displaySelection()
	{
		System.out.println("/n==select==");
		System.out.println("1. List all books");
		System.out.println("2. Add 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)
			return n;
		return 0;
	}

	/**
	 * 增加一本书到数据库和索引中
	 * @param book
	 */
	private static void add(Book book)
	{
		db.add(book);
		searcher.index(book);
	}

	/**
	 * 打印出数据库中的所有书籍列表
	 */
	public static void listBooks()
	{
		System.out.println("==Database==");
		int n =1;
		for (Book book :db)
		{
			System.out.println(n+")"+book);
			n++;
		}
	}

	/**
	 * 根据用户录入,增加一本书到数据库和索引中
	 */
	public static 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 static void deleteBook()
	{
		listBooks();
		System.out.println("Book index: ");
		int n = readKey();
		Book book = db.remove(n-1);
		searcher.unIndex(book);
	}

	/**
	 * 根据输入的关键字搜索书籍
	 */
	public static void searchBook()
	{
		String queryString = readLine(" Enter keyword: ");
		List<Book> books = searcher.search(queryString);
		System.out.println(" ====search results:"+books.size()+"====");
		for (Book book :books)
		{
			System.out.println(book);
		}
	}

	public static int readKey()
	{
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		try
		{
			int n = reader.read();
			n=Integer.parseInt(Character.toString((char)n));
			return n;
		}catch(Exception e)
		{
			throw new RuntimeException();
		}
	}
	
	public static String readLine(String propt)
	{
		System.out.println(propt);
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		try{
			return reader.readLine();
		}catch(Exception e)
		{
			throw new RuntimeException();
		}
	}
}

 

  转载请标明出处 http://blog.csdn.net/shimiso 

技术交流群:361579846

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值