//須要導入的jar包:commons-logging.jar, compass-2.2.0.jar, lucene-core.jar @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; } @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; } } public class Searcher { protected Compass compass; public Searcher() { } 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(); 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 (RuntimeException e) { tx.rollback(); e.printStackTrace(); } 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(); e.printStackTrace(); } finally { if (session != null) { session.close(); } } return null; } } //測試 public class Main { static List<Book> db = new ArrayList<Book>(); static Searcher searcher = new Searcher("index"); public static void main(String[] args) { db.add(new Book("1", "Thinking in Java", "Bruce", 109.0f)); db.add(new Book("2", "Effective Java", "Joshua", 12.4f)); db.add(new Book("3", "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 bookID = readLine(" BookID: "); String title = readLine(" Title: "); String author = readLine(" Author: "); String price = readLine(" Price: "); Book book = new Book(bookID, 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(); } } }