`

【转】基于Lucene框架 Compass 的使用例子

 
阅读更多

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:

 

01 package com.sse.first;
02  
03 import org.compass.annotations.Index;
04 import org.compass.annotations.Searchable;
05 import org.compass.annotations.SearchableId;
06 import org.compass.annotations.SearchableProperty;
07 import org.compass.annotations.Store;
08  
09 @Searchable
10 public class Book {
11  
12 private String id;
13 private String title;
14 private String author;
15 private float price;
16  
17 public Book(){}
18  
19 public Book(String id, String title, String author, float price){
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 public void setId(String id) {
31 this.id = id;
32 }
33  
34 @SearchableProperty(boost=2.0F, index=Index.TOKENIZED, store=Store.YES)
35 public String getTitle() {
36 return title;
37 }
38 public void setTitle(String title) {
39 this.title = title;
40 }
41  
42 @SearchableProperty(index=Index.TOKENIZED, store=Store.YES)
43 public String getAuthor() {
44 return author;
45 }
46 public void setAuthor(String author) {
47 this.author = author;
48 }
49  
50 @SearchableProperty(index=Index.NO, store=Store.YES)
51 public float getPrice() {
52 return price;
53 }
54 public void setPrice(float price) {
55 this.price = price;
56 }
57  
58 @Override
59 public String toString() {
60 return "[ "+ id +" ] " + title +" -- " + author + " $ " + price;
61 }
62  
63  
64 }

 

主搜索服务Searcher.java:

package com.sse.first;

001 import java.util.ArrayList;
002 import java.util.Collections;
003 import java.util.List;
004  
005 import org.compass.annotations.config.CompassAnnotationsConfiguration;
006 import org.compass.core.Compass;
007 import org.compass.core.CompassException;
008 import org.compass.core.CompassHits;
009 import org.compass.core.CompassSession;
010 import org.compass.core.CompassTransaction;
011  
012 public class Searcher {
013  
014 private Compass compass;
015  
016 /**
017 * 初始化检索器
018 * @param path
019 */
020 public Searcher(String path){
021 compass = new CompassAnnotationsConfiguration()
022 .setConnection(path)
023 .addClass(Book.class)
024 .setSetting("compass.engine.highlighter.default.formatter.simple.pre", "<b>")
025 .setSetting("compass.engine.highlighter.default.formatter.simple.post", "</b>")
026 .buildCompass();
027  
028 Runtime.getRuntime().addShutdownHook(new Thread(){
029 public void run(){
030 compass.close();
031 }
032 });
033 }
034  
035 /**
036 * 建立数据索引
037 * @param book
038 */
039 public void index(Book book){
040 System.out.println("index book : " + book);
041 CompassSession session = null;
042 CompassTransaction tx = null;
043  
044 try {
045 session = compass.openSession();
046 tx = session.beginTransaction();
047  
048 session.create(book);
049 tx.commit();
050 } catch (CompassException e) {
051 tx.rollback();
052 e.printStackTrace();
053 } finally{
054 if ( session != null )
055 session.close();
056 }
057  
058 }
059  
060 /**
061 * 删除索引
062 * @param book
063 */
064 public void unIndex(Book book){
065 CompassSession session = null;
066 CompassTransaction tx = null;
067  
068 try {
069 session = compass.openSession();
070 tx = session.beginTransaction();
071  
072 session.delete(book);
073 tx.commit();
074 } catch (CompassException e) {
075 tx.rollback();
076 e.printStackTrace();
077 } finally{
078 if ( session != null )
079 session.close();
080 }
081  
082 }
083  
084 /**
085 * 重置对象索引
086 * @param book
087 */
088 public void reIndex(Book book){
089 unIndex(book);
090 index(book);
091 }
092  
093 /**
094 * 查询
095 * @param q
096 * @return
097 */
098 @SuppressWarnings("unchecked")
099 public List<Book> search(String q){
100 CompassSession session = null;
101 CompassTransaction tx = null;
102  
103 try {
104 session = compass.openSession();
105 tx = session.beginTransaction();
106 CompassHits hits = session.find(q);
107  
108 int n = hits.length();
109 if ( n == 0 )
110 return Collections.EMPTY_LIST;
111  
112 List<Book> books = new ArrayList<Book>(n);
113 for (int i = 0; i < n; i++)
114 books.add((Book)hits.data(i));
115  
116 hits.close();
117 tx.commit();
118 return books;
119 } catch (CompassException e) {
120 tx.rollback();
121 e.printStackTrace();
122 }
123 return Collections.EMPTY_LIST;
124 }
125 }

 

 

测试主入口main.java:

001 package com.sse.first;
002  
003 import java.io.BufferedReader;
004 import java.io.File;
005 import java.io.InputStreamReader;
006 import java.util.ArrayList;
007 import java.util.Iterator;
008 import java.util.List;
009 import java.util.UUID;
010  
011 import com.Const;
012  
013 //import javax.swing.JOptionPane;
014  
015 public class Main {
016  
017 static List<Book> db = new ArrayList<Book>();
018 static Searcher search = new Searcher(Const.indexPath);
019  
020 public static void main(String[] args) {
021 // deleteAllBooks();
022  
023 add(new Book(UUID.randomUUID().toString(), "Thinking in Java", "Bruce", 10.9f));
024 add(new Book(UUID.randomUUID().toString(), "Effective Java", "Joshua", 12.4f));
025 add(new Book(UUID.randomUUID().toString(), "Java Thread Programming", "Pail", 25.6f));
026  
027 Runtime.getRuntime().addShutdownHook(new Thread(){
028 public void run(){
029 deleteAllIndex(null);
030 }
031 });
032  
033 int n;
034 do{
035 n = displaySelection();
036 switch(n){
037 case 1 :
038 listBooks();
039 break;
040 case 2 :
041 addBook();
042 break;
043 case 3 :
044 deleteBook();
045 break;
046 case 4 :
047 searchBook();
048 break;
049 case 5 :
050 return;
051 }
052 }while ( n != 0 );
053 }
054  
055 private static int displaySelection() {
056 System.out.println("\n=====select index ======= ");
057 System.out.println("1. List all books ");
058 System.out.println("2. Add new book");
059 System.out.println("3. Delete book");
060 System.out.println("4. Search book");
061 System.out.println("5. Exit");
062 int n = readKey();
063 if ( n >= 1 && n <= 5 )
064 return n;
065 return 0;
066 }
067  
068 /**
069 * 从控制台读数字作为参数
070 * @return
071 */
072 private static int readKey() {
073 // String ss=JOptionPane.showInputDialog("","Select Index :");
074 // try{
075 // return Integer.parseInt(ss);
076 // }catch(Exception e){
077 // System.out.println("输入的数据类型不对,程序将退出");
078 // System.exit(0);
079 // }
080  
081 System.out.println("Select Index :");
082 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
083 try{
084 return Integer.parseInt(reader.readLine());
085 }catch(Exception e){
086 throw new RuntimeException();
087 }
088 }
089  
090 /**
091 * 从控制台读字符串作为参数
092 * @param prompt
093 * @return
094 */
095 private static String readLine(String prompt) {
096 // return JOptionPane.showInputDialog("" , prompt);
097 System.out.println(prompt);
098 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
099 try{
100 return reader.readLine();
101 }catch(Exception e){
102 throw new RuntimeException();
103 }
104 }
105  
106 /**
107 * 检索数据
108 */
109 private static void searchBook() {
110 String q = readLine("Enter keyword: ");
111 List<Book> books = search.search(q);
112 System.out.println("============ Search Results: " + books.size() + " ======== ");
113 for (Book book : books ) {
114 System.out.println(book);
115 }
116  
117 }
118  
119 /**
120 * 删除数据,并删除索引
121 */
122 private static void deleteBook() {
123 listBooks();
124 System.out.println("Book Index: ");
125 int n = readKey();
126 Book book = db.remove(n - 1 );
127 search.unIndex(book);
128 }
129  
130 // private static void deleteAllBooks(){
131 // for (Book book : db ){
132 // db.remove(book);
133 // search.unIndex(book);
134 // }
135 // }
136  
137 /**
138 * 删除所有的索引文件
139 * @param file
140 */
141 private static void deleteAllIndex(File file){
142 if ( file == null)
143 file = new File(Const.indexPath);
144  
145 if ( file.exists() ){
146 if ( file.isFile() )
147 file.delete();
148 else if ( file.isDirectory() ){
149 File files[] = file.listFiles();
150 for (File temp : files){
151 deleteAllIndex(temp);
152 }
153 }
154 }
155 }
156  
157 /**
158 * 添加新的数据
159 */
160 private static void addBook() {
161 String title = readLine(" Title: ");
162 String author = readLine("Author: ");
163 String price = readLine(" Price: ");
164  
165 Book book = new Book(UUID.randomUUID().toString(), title, author,Float.parseFloat(price));
166 add(book);
167 }
168  
169 /**
170 * 列出所有的数据
171 */
172 private static void listBooks(){
173 System.out.println(" =======DataBase=========");
174 for (Iterator<Book> iterator = db.iterator(); iterator.hasNext();) {
175 Book book = (Book) iterator.next();
176 System.out.println(book.toString());
177 }
178 }
179  
180 /**
181 * 添加数据并建立索引
182 * @param book
183 */
184 private static void add(Book book){
185 db.add(book);
186 search.index(book);
187 }
188  
189 }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics