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(書籍)類,這個類就是我們要搜索的對象,其完整代碼如下:
- 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 Stringid; //編號
- private Stringtitle; //標題
- private Stringauthor; //作者
- private float price; //價格
- public Book(){
- }
- public Book(Stringid,Stringtitle,Stringauthor, float price){
- super ();
- this .id=id;
- this .title=title;
- this .author=author;
- this .price=price;
- }
- @SearchableId
- public StringgetId(){
- return id;
- }
- @SearchableProperty (boost= 2 .0F,index=Index.TOKENIZED,store=Store.YES)
- public StringgetTitle(){
- return title;
- }
- @SearchableProperty (index=Index.TOKENIZED,store=Store.YES)
- public StringgetAuthor(){
- return author;
- }
- @SearchableProperty (index=Index.NO,store=Store.YES)
- public float getPrice(){
- return price;
- }
- public void setId(Stringid){
- this .id=id;
- }
- public void setTitle(Stringtitle){
- this .title=title;
- }
- public void setAuthor(Stringauthor){
- this .author=author;
- }
- public void setPrice( float price){
- this .price=price;
- }
- @Override
- public StringtoString(){
- return "[" +id+ "]" +title+ "-" +author+ "$" +price;
- }
- }
這里有幾個要注意的地方:@Searchable表示該類的對象是可被搜索的;@SearchableId表示索引建立的id;@SearchableProperty表示此字段可以被索引、被檢索;對于Index,Store在這里就不作介紹了,不熟悉的朋友可以去看看Lucene API。
步驟四:新建一個Searcher類,該類封裝了對索引庫的一些操作,包括新建索引,刪除索引,重建索引,搜索等等。完整代碼如下:
- 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 Compasscompass;
- public Searcher()
- {
- }
- /**
- *初始化Compass
- *@parampath
- */
- public Searcher(Stringpath)
- {
- compass= new CompassAnnotationsConfiguration().setConnection(path).addClass(Book. class ).setSetting( "compass.engine.highlighter.default.formatter.simple.pre" , "<fontcolor='red'>" ).setSetting(
- "compass.engine.highlighter.default.formatter.simple.post" , "</font>" ).buildCompass();
- Runtime.getRuntime().addShutdownHook( new Thread()
- {
- public void run()
- {
- compass.close();
- }
- });
- }
- /**
- *新建索引
- *@parambook
- */
- public void index(Bookbook)
- {
- CompassSessionsession= null ;
- CompassTransactiontx= null ;
- try
- {
- session=compass.openSession();
- tx=session.beginTransaction();
- session.create(book);
- tx.commit();
- } catch (RuntimeExceptione)
- {
- if (tx!= null )
- tx.rollback();
- throw e;
- } finally
- {
- if (session!= null )
- {
- session.close();
- }
- }
- }
- /**
- *刪除索引
- *@parambook
- */
- public void unIndex(Bookbook)
- {
- CompassSessionsession= null ;
- CompassTransactiontx= null ;
- try
- {
- session=compass.openSession();
- tx=session.beginTransaction();
- session.delete(book);
- tx.commit();
- } catch (RuntimeExceptione)
- {
- tx.rollback();
- throw e;
- } finally
- {
- if (session!= null )
- {
- session.close();
- }
- }
- }
- /**
- *重建索引
- *@parambook
- */
- public void reIndex(Bookbook)
- {
- unIndex(book);
- index(book);
- }
- /**
- *搜索
- *@paramqueryString
- *@return
- */
- public List<Book>search(StringqueryString)
- {
- CompassSessionsession= null ;
- CompassTransactiontx= null ;
- try
- {
- session=compass.openSession();
- tx=session.beginTransaction();
- CompassHitshits=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 (RuntimeExceptione)
- {
- tx.rollback();
- throw e;
- } finally
- {
- if (session!= null )
- {
- session.close();
- }
- }
- }
- }
步驟五:新建一個測試類進行測試.完整源碼如下:
- 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 Searchersearcher= new Searcher( "E:/index" );
- public static void main(String[]args)
- {
- add( new Book(UUID.randomUUID().toString(), "ThinkinginJava" , "Bruce" , 109 .0f));
- add( new Book(UUID.randomUUID().toString(), "EffectiveJava" , "Joshua" , 12 .4f));
- add( new Book(UUID.randomUUID().toString(), "JavaThreadPrograming" , "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.Listallbooks" );
- System.out.println( "2.Addbook" );
- System.out.println( "3.Deletebook" );
- System.out.println( "4.Searchbook" );
- System.out.println( "5.Exit" );
- int n=readKey();
- if (n>= 1 &&n<= 5 )
- return n;
- return 0 ;
- }
- /**
- *增加一本書到數據庫和索引中
- *@parambook
- */
- private static void add(Bookbook)
- {
- db.add(book);
- searcher.index(book);
- }
- /**
- *打印出數據庫中的所有書籍列表
- */
- public static void listBooks()
- {
- System.out.println( "==Database==" );
- int n= 1 ;
- for (Bookbook:db)
- {
- System.out.println(n+ ")" +book);
- n++;
- }
- }
- /**
- *根據用戶錄入,增加一本書到數據庫和索引中
- */
- public static void addBook()
- {
- Stringtitle=readLine( "Title:" );
- Stringauthor=readLine( "Author:" );
- Stringprice=readLine( "Price:" );
- Bookbook= new Book(UUID.randomUUID().toString(),title,author,Float.valueOf(price));
- add(book);
- }
- /**
- *刪除一本書,同時刪除數據庫,索引庫中的
- */
- public static void deleteBook()
- {
- listBooks();
- System.out.println( "Bookindex:" );
- int n=readKey();
- Bookbook=db.remove(n- 1 );
- searcher.unIndex(book);
- }
- /**
- *根據輸入的關鍵字搜索書籍
- */
- public static void searchBook()
- {
- StringqueryString=readLine( "Enterkeyword:" );
- List<Book>books=searcher.search(queryString);
- System.out.println( "====searchresults:" +books.size()+ "====" );
- for (Bookbook:books)
- {
- System.out.println(book);
- }
- }
- public static int readKey()
- {
- BufferedReaderreader= new BufferedReader( new InputStreamReader(System.in));
- try
- {
- int n=reader.read();
- n=Integer.parseInt(Character.toString(( char )n));
- return n;
- } catch (Exceptione)
- {
- throw new RuntimeException();
- }
- }
- public static StringreadLine(Stringpropt)
- {
- System.out.println(propt);
- BufferedReaderreader= new BufferedReader( new InputStreamReader(System.in));
- try {
- return reader.readLine();
- } catch (Exceptione)
- {
- throw new RuntimeException();
- }
- }
- }
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
