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. importorg.compass.annotations.Index;
  2. importorg.compass.annotations.Searchable;
  3. importorg.compass.annotations.SearchableId;
  4. importorg.compass.annotations.SearchableProperty;
  5. importorg.compass.annotations.Store;
  6. @Searchable
  7. publicclassBook{
  8. privateStringid;//编号
  9. privateStringtitle;//标题
  10. privateStringauthor;//作者
  11. privatefloatprice;//价格
  12. publicBook(){
  13. }
  14. publicBook(Stringid,Stringtitle,Stringauthor,floatprice){
  15. super();
  16. this.id=id;
  17. this.title=title;
  18. this.author=author;
  19. this.price=price;
  20. }
  21. @SearchableId
  22. publicStringgetId(){
  23. returnid;
  24. }
  25. @SearchableProperty(boost=2.0F,index=Index.TOKENIZED,store=Store.YES)
  26. publicStringgetTitle(){
  27. returntitle;
  28. }
  29. @SearchableProperty(index=Index.TOKENIZED,store=Store.YES)
  30. publicStringgetAuthor(){
  31. returnauthor;
  32. }
  33. @SearchableProperty(index=Index.NO,store=Store.YES)
  34. publicfloatgetPrice(){
  35. returnprice;
  36. }
  37. publicvoidsetId(Stringid){
  38. this.id=id;
  39. }
  40. publicvoidsetTitle(Stringtitle){
  41. this.title=title;
  42. }
  43. publicvoidsetAuthor(Stringauthor){
  44. this.author=author;
  45. }
  46. publicvoidsetPrice(floatprice){
  47. this.price=price;
  48. }
  49. @Override
  50. publicStringtoString(){
  51. return"["+id+"]"+title+"-"+author+"$"+price;
  52. }
  53. }


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

Java代码
  1. importjava.util.ArrayList;
  2. importjava.util.Collections;
  3. importjava.util.List;
  4. importorg.compass.annotations.config.CompassAnnotationsConfiguration;
  5. importorg.compass.core.Compass;
  6. importorg.compass.core.CompassHits;
  7. importorg.compass.core.CompassSession;
  8. importorg.compass.core.CompassTransaction;
  9. publicclassSearcher
  10. {
  11. protectedCompasscompass;
  12. publicSearcher()
  13. {
  14. }
  15. /**
  16. *初始化Compass
  17. *@parampath
  18. */
  19. publicSearcher(Stringpath)
  20. {
  21. compass=newCompassAnnotationsConfiguration().setConnection(path).addClass(Book.class).setSetting("compass.engine.highlighter.default.formatter.simple.pre","<fontcolor='red'>").setSetting(
  22. "compass.engine.highlighter.default.formatter.simple.post","</font>").buildCompass();
  23. Runtime.getRuntime().addShutdownHook(newThread()
  24. {
  25. publicvoidrun()
  26. {
  27. compass.close();
  28. }
  29. });
  30. }
  31. /**
  32. *新建索引
  33. *@parambook
  34. */
  35. publicvoidindex(Bookbook)
  36. {
  37. CompassSessionsession=null;
  38. CompassTransactiontx=null;
  39. try
  40. {
  41. session=compass.openSession();
  42. tx=session.beginTransaction();
  43. session.create(book);
  44. tx.commit();
  45. }catch(RuntimeExceptione)
  46. {
  47. if(tx!=null)
  48. tx.rollback();
  49. throwe;
  50. }finally
  51. {
  52. if(session!=null)
  53. {
  54. session.close();
  55. }
  56. }
  57. }
  58. /**
  59. *删除索引
  60. *@parambook
  61. */
  62. publicvoidunIndex(Bookbook)
  63. {
  64. CompassSessionsession=null;
  65. CompassTransactiontx=null;
  66. try
  67. {
  68. session=compass.openSession();
  69. tx=session.beginTransaction();
  70. session.delete(book);
  71. tx.commit();
  72. }catch(RuntimeExceptione)
  73. {
  74. tx.rollback();
  75. throwe;
  76. }finally
  77. {
  78. if(session!=null)
  79. {
  80. session.close();
  81. }
  82. }
  83. }
  84. /**
  85. *重建索引
  86. *@parambook
  87. */
  88. publicvoidreIndex(Bookbook)
  89. {
  90. unIndex(book);
  91. index(book);
  92. }
  93. /**
  94. *搜索
  95. *@paramqueryString
  96. *@return
  97. */
  98. publicList<Book>search(StringqueryString)
  99. {
  100. CompassSessionsession=null;
  101. CompassTransactiontx=null;
  102. try
  103. {
  104. session=compass.openSession();
  105. tx=session.beginTransaction();
  106. CompassHitshits=session.find(queryString);
  107. intn=hits.length();
  108. if(0==n)
  109. {
  110. returnCollections.emptyList();
  111. }
  112. List<Book>books=newArrayList<Book>();
  113. for(inti=0;i<n;i++)
  114. {
  115. books.add((Book)hits.data(i));
  116. }
  117. hits.close();
  118. tx.commit();
  119. returnbooks;
  120. }catch(RuntimeExceptione)
  121. {
  122. tx.rollback();
  123. throwe;
  124. }finally
  125. {
  126. if(session!=null)
  127. {
  128. session.close();
  129. }
  130. }
  131. }
  132. }


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

Java代码
  1. importjava.io.BufferedReader;
  2. importjava.io.InputStreamReader;
  3. importjava.util.ArrayList;
  4. importjava.util.List;
  5. importjava.util.UUID;
  6. publicclassMain
  7. {
  8. staticList<Book>db=newArrayList<Book>();
  9. staticSearchersearcher=newSearcher("E:/index");
  10. publicstaticvoidmain(String[]args)
  11. {
  12. add(newBook(UUID.randomUUID().toString(),"ThinkinginJava","Bruce",109.0f));
  13. add(newBook(UUID.randomUUID().toString(),"EffectiveJava","Joshua",12.4f));
  14. add(newBook(UUID.randomUUID().toString(),"JavaThreadPrograming","Paul",25.8f));
  15. intn;
  16. do
  17. {
  18. n=displaySelection();
  19. switch(n)
  20. {
  21. case1:
  22. listBooks();
  23. break;
  24. case2:
  25. addBook();
  26. break;
  27. case3:
  28. deleteBook();
  29. break;
  30. case4:
  31. searchBook();
  32. break;
  33. case5:
  34. return;
  35. }
  36. }while(n!=0);
  37. }
  38. staticintdisplaySelection()
  39. {
  40. System.out.println("\n==select==");
  41. System.out.println("1.Listallbooks");
  42. System.out.println("2.Addbook");
  43. System.out.println("3.Deletebook");
  44. System.out.println("4.Searchbook");
  45. System.out.println("5.Exit");
  46. intn=readKey();
  47. if(n>=1&&n<=5)
  48. returnn;
  49. return0;
  50. }
  51. /**
  52. *增加一本书到数据库和索引中
  53. *@parambook
  54. */
  55. privatestaticvoidadd(Bookbook)
  56. {
  57. db.add(book);
  58. searcher.index(book);
  59. }
  60. /**
  61. *打印出数据库中的所有书籍列表
  62. */
  63. publicstaticvoidlistBooks()
  64. {
  65. System.out.println("==Database==");
  66. intn=1;
  67. for(Bookbook:db)
  68. {
  69. System.out.println(n+")"+book);
  70. n++;
  71. }
  72. }
  73. /**
  74. *根据用户录入,增加一本书到数据库和索引中
  75. */
  76. publicstaticvoidaddBook()
  77. {
  78. Stringtitle=readLine("Title:");
  79. Stringauthor=readLine("Author:");
  80. Stringprice=readLine("Price:");
  81. Bookbook=newBook(UUID.randomUUID().toString(),title,author,Float.valueOf(price));
  82. add(book);
  83. }
  84. /**
  85. *删除一本书,同时删除数据库,索引库中的
  86. */
  87. publicstaticvoiddeleteBook()
  88. {
  89. listBooks();
  90. System.out.println("Bookindex:");
  91. intn=readKey();
  92. Bookbook=db.remove(n-1);
  93. searcher.unIndex(book);
  94. }
  95. /**
  96. *根据输入的关键字搜索书籍
  97. */
  98. publicstaticvoidsearchBook()
  99. {
  100. StringqueryString=readLine("Enterkeyword:");
  101. List<Book>books=searcher.search(queryString);
  102. System.out.println("====searchresults:"+books.size()+"====");
  103. for(Bookbook:books)
  104. {
  105. System.out.println(book);
  106. }
  107. }
  108. publicstaticintreadKey()
  109. {
  110. BufferedReaderreader=newBufferedReader(newInputStreamReader(System.in));
  111. try
  112. {
  113. intn=reader.read();
  114. n=Integer.parseInt(Character.toString((char)n));
  115. returnn;
  116. }catch(Exceptione)
  117. {
  118. thrownewRuntimeException();
  119. }
  120. }
  121. publicstaticStringreadLine(Stringpropt)
  122. {
  123. System.out.println(propt);
  124. BufferedReaderreader=newBufferedReader(newInputStreamReader(System.in));
  125. try{
  126. returnreader.readLine();
  127. }catch(Exceptione)
  128. {
  129. thrownewRuntimeException();
  130. }
  131. }
  132. }

你可能感兴趣的:(eclipse,框架,Hibernate,ssh,Lucene)