基于Lucene框架 Compass 的使用例子

fmms 12年前

Compass 资源下载地址:

http://sourceforge.net/projects/compass/files/compass/2.2.0/compass-2.2.0-with-dependencies.zip/download

选取三个jar包:commons-logging.jar, compass-2.2.0.jar, lucene-core.jar.

使用OSEM(Object/SearchEngine Mapping)映射方案

 

映射的实体对象Book.java:

package com.sse.first;    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){  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=2.0F, index=Index.TOKENIZED, store=Store.YES)  public String getTitle() {  return title;  }  public void setTitle(String title) {  this.title = title;  }    @SearchableProperty(index=Index.TOKENIZED, store=Store.YES)  public String getAuthor() {  return author;  }  public void setAuthor(String author) {  this.author = author;  }    @SearchableProperty(index=Index.NO, store=Store.YES)  public float getPrice() {  return price;  }  public void setPrice(float price) {  this.price = price;  }    @Override  public String toString() {  return "[ "+ id +" ] " + title +" -- " + author + " $ " + price;  }      }     

主搜索服务Searcher.java:

package com.sse.first;

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.CompassException;  import org.compass.core.CompassHits;  import org.compass.core.CompassSession;  import org.compass.core.CompassTransaction;    public class Searcher {    private Compass compass;    /**  * 初始化检索器  * @param path  */  public Searcher(String path){  compass = new CompassAnnotationsConfiguration()  .setConnection(path)  .addClass(Book.class)  .setSetting("compass.engine.highlighter.default.formatter.simple.pre", "<b>")  .setSetting("compass.engine.highlighter.default.formatter.simple.post", "</b>")  .buildCompass();    Runtime.getRuntime().addShutdownHook(new Thread(){  public void run(){  compass.close();  }  });  }    /**  * 建立数据索引  * @param book  */  public void index(Book book){  System.out.println("index book : " + book);  CompassSession session = null;  CompassTransaction tx = null;    try {  session = compass.openSession();  tx = session.beginTransaction();    session.create(book);  tx.commit();  } catch (CompassException e) {  tx.rollback();  e.printStackTrace();  } 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 (CompassException e) {  tx.rollback();  e.printStackTrace();  } finally{  if ( session != null )  session.close();  }    }    /**  * 重置对象索引  * @param book  */  public void reIndex(Book book){  unIndex(book);  index(book);  }    /**  * 查询  * @param q  * @return  */  @SuppressWarnings("unchecked")  public List<Book> search(String q){  CompassSession session = null;  CompassTransaction tx = null;    try {  session = compass.openSession();  tx = session.beginTransaction();  CompassHits hits = session.find(q);    int n = hits.length();  if ( n == 0 )  return Collections.EMPTY_LIST;    List<Book> books = new ArrayList<Book>(n);  for (int i = 0; i < n; i++)  books.add((Book)hits.data(i));    hits.close();  tx.commit();  return books;  } catch (CompassException e) {  tx.rollback();  e.printStackTrace();  }  return Collections.EMPTY_LIST;  }  }

 

测试主入口main.java:

package com.sse.first;    import java.io.BufferedReader;  import java.io.File;  import java.io.InputStreamReader;  import java.util.ArrayList;  import java.util.Iterator;  import java.util.List;  import java.util.UUID;    import com.Const;    //import javax.swing.JOptionPane;    public class Main {    static List<Book> db = new ArrayList<Book>();  static Searcher search = new Searcher(Const.indexPath);    public static void main(String[] args) {  // deleteAllBooks();    add(new Book(UUID.randomUUID().toString(), "Thinking in Java", "Bruce", 10.9f));  add(new Book(UUID.randomUUID().toString(), "Effective Java", "Joshua", 12.4f));  add(new Book(UUID.randomUUID().toString(), "Java Thread Programming", "Pail", 25.6f));    Runtime.getRuntime().addShutdownHook(new Thread(){  public void run(){  deleteAllIndex(null);  }  });    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 );  }    private static int displaySelection() {  System.out.println("\n=====select index ======= ");  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 )  return n;  return 0;  }    /**  * 从控制台读数字作为参数  * @return  */  private static int readKey() {  // String ss=JOptionPane.showInputDialog("","Select Index :");  // try{  // return Integer.parseInt(ss);  // }catch(Exception e){  // System.out.println("输入的数据类型不对,程序将退出");  // System.exit(0);  // }    System.out.println("Select Index :");  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));  try{  return Integer.parseInt(reader.readLine());  }catch(Exception e){  throw new RuntimeException();  }  }    /**  * 从控制台读字符串作为参数  * @param prompt  * @return  */  private static String readLine(String prompt) {  // return JOptionPane.showInputDialog("" , prompt);  System.out.println(prompt);  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));  try{  return reader.readLine();  }catch(Exception e){  throw new RuntimeException();  }  }    /**  * 检索数据  */  private static void searchBook() {  String q = readLine("Enter keyword: ");  List<Book> books = search.search(q);  System.out.println("============ Search Results: " + books.size() + " ======== ");  for (Book book : books ) {  System.out.println(book);  }    }    /**  * 删除数据,并删除索引  */  private static void deleteBook() {  listBooks();  System.out.println("Book Index: ");  int n = readKey();  Book book = db.remove(n - 1 );  search.unIndex(book);  }    // private static void deleteAllBooks(){  // for (Book book : db ){  // db.remove(book);  // search.unIndex(book);  // }  // }    /**  * 删除所有的索引文件  * @param file  */  private static void deleteAllIndex(File file){  if ( file == null)  file = new File(Const.indexPath);    if ( file.exists() ){  if ( file.isFile() )  file.delete();  else if ( file.isDirectory() ){  File files[] = file.listFiles();  for (File temp : files){  deleteAllIndex(temp);  }  }  }  }    /**  * 添加新的数据  */  private 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.parseFloat(price));  add(book);  }    /**  * 列出所有的数据  */  private static void listBooks(){  System.out.println(" =======DataBase=========");  for (Iterator<Book> iterator = db.iterator(); iterator.hasNext();) {  Book book = (Book) iterator.next();  System.out.println(book.toString());  }  }    /**  * 添加数据并建立索引  * @param book  */  private static void add(Book book){  db.add(book);  search.index(book);  }    }