Compass入门指南(二)

系统 2378 0

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. import org.compass.annotations.Index;
  2. import org.compass.annotations.Searchable;
  3. import org.compass.annotations.SearchableId;
  4. import org.compass.annotations.SearchableProperty;
  5. import org.compass.annotations.Store;
  6. @Searchable
  7. public class Book{
  8. private Stringid; //编号
  9. private Stringtitle; //标题
  10. private Stringauthor; //作者
  11. private float price; //价格
  12. public Book(){
  13. }
  14. public Book(Stringid,Stringtitle,Stringauthor, float price){
  15. super ();
  16. this .id=id;
  17. this .title=title;
  18. this .author=author;
  19. this .price=price;
  20. }
  21. @SearchableId
  22. public StringgetId(){
  23. return id;
  24. }
  25. @SearchableProperty (boost= 2 .0F,index=Index.TOKENIZED,store=Store.YES)
  26. public StringgetTitle(){
  27. return title;
  28. }
  29. @SearchableProperty (index=Index.TOKENIZED,store=Store.YES)
  30. public StringgetAuthor(){
  31. return author;
  32. }
  33. @SearchableProperty (index=Index.NO,store=Store.YES)
  34. public float getPrice(){
  35. return price;
  36. }
  37. public void setId(Stringid){
  38. this .id=id;
  39. }
  40. public void setTitle(Stringtitle){
  41. this .title=title;
  42. }
  43. public void setAuthor(Stringauthor){
  44. this .author=author;
  45. }
  46. public void setPrice( float price){
  47. this .price=price;
  48. }
  49. @Override
  50. public StringtoString(){
  51. return "[" +id+ "]" +title+ "-" +author+ "$" +price;
  52. }
  53. }


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

Java代码
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.List;
  4. import org.compass.annotations.config.CompassAnnotationsConfiguration;
  5. import org.compass.core.Compass;
  6. import org.compass.core.CompassHits;
  7. import org.compass.core.CompassSession;
  8. import org.compass.core.CompassTransaction;
  9. public class Searcher
  10. {
  11. protected Compasscompass;
  12. public Searcher()
  13. {
  14. }
  15. /**
  16. *初始化Compass
  17. *@parampath
  18. */
  19. public Searcher(Stringpath)
  20. {
  21. compass= new CompassAnnotationsConfiguration().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( new Thread()
  24. {
  25. public void run()
  26. {
  27. compass.close();
  28. }
  29. });
  30. }
  31. /**
  32. *新建索引
  33. *@parambook
  34. */
  35. public void index(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. throw e;
  50. } finally
  51. {
  52. if (session!= null )
  53. {
  54. session.close();
  55. }
  56. }
  57. }
  58. /**
  59. *删除索引
  60. *@parambook
  61. */
  62. public void unIndex(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. throw e;
  76. } finally
  77. {
  78. if (session!= null )
  79. {
  80. session.close();
  81. }
  82. }
  83. }
  84. /**
  85. *重建索引
  86. *@parambook
  87. */
  88. public void reIndex(Bookbook)
  89. {
  90. unIndex(book);
  91. index(book);
  92. }
  93. /**
  94. *搜索
  95. *@paramqueryString
  96. *@return
  97. */
  98. public List<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. int n=hits.length();
  108. if ( 0 ==n)
  109. {
  110. return Collections.emptyList();
  111. }
  112. List<Book>books= new ArrayList<Book>();
  113. for ( int i= 0 ;i<n;i++)
  114. {
  115. books.add((Book)hits.data(i));
  116. }
  117. hits.close();
  118. tx.commit();
  119. return books;
  120. } catch (RuntimeExceptione)
  121. {
  122. tx.rollback();
  123. throw e;
  124. } finally
  125. {
  126. if (session!= null )
  127. {
  128. session.close();
  129. }
  130. }
  131. }
  132. }


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

Java代码
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.UUID;
  6. public class Main
  7. {
  8. static List<Book>db= new ArrayList<Book>();
  9. static Searchersearcher= new Searcher( "E:/index" );
  10. public static void main(String[]args)
  11. {
  12. add( new Book(UUID.randomUUID().toString(), "ThinkinginJava" , "Bruce" , 109 .0f));
  13. add( new Book(UUID.randomUUID().toString(), "EffectiveJava" , "Joshua" , 12 .4f));
  14. add( new Book(UUID.randomUUID().toString(), "JavaThreadPrograming" , "Paul" , 25 .8f));
  15. int n;
  16. do
  17. {
  18. n=displaySelection();
  19. switch (n)
  20. {
  21. case 1 :
  22. listBooks();
  23. break ;
  24. case 2 :
  25. addBook();
  26. break ;
  27. case 3 :
  28. deleteBook();
  29. break ;
  30. case 4 :
  31. searchBook();
  32. break ;
  33. case 5 :
  34. return ;
  35. }
  36. } while (n!= 0 );
  37. }
  38. static int displaySelection()
  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. int n=readKey();
  47. if (n>= 1 &&n<= 5 )
  48. return n;
  49. return 0 ;
  50. }
  51. /**
  52. *增加一本书到数据库和索引中
  53. *@parambook
  54. */
  55. private static void add(Bookbook)
  56. {
  57. db.add(book);
  58. searcher.index(book);
  59. }
  60. /**
  61. *打印出数据库中的所有书籍列表
  62. */
  63. public static void listBooks()
  64. {
  65. System.out.println( "==Database==" );
  66. int n= 1 ;
  67. for (Bookbook:db)
  68. {
  69. System.out.println(n+ ")" +book);
  70. n++;
  71. }
  72. }
  73. /**
  74. *根据用户录入,增加一本书到数据库和索引中
  75. */
  76. public static void addBook()
  77. {
  78. Stringtitle=readLine( "Title:" );
  79. Stringauthor=readLine( "Author:" );
  80. Stringprice=readLine( "Price:" );
  81. Bookbook= new Book(UUID.randomUUID().toString(),title,author,Float.valueOf(price));
  82. add(book);
  83. }
  84. /**
  85. *删除一本书,同时删除数据库,索引库中的
  86. */
  87. public static void deleteBook()
  88. {
  89. listBooks();
  90. System.out.println( "Bookindex:" );
  91. int n=readKey();
  92. Bookbook=db.remove(n- 1 );
  93. searcher.unIndex(book);
  94. }
  95. /**
  96. *根据输入的关键字搜索书籍
  97. */
  98. public static void searchBook()
  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. public static int readKey()
  109. {
  110. BufferedReaderreader= new BufferedReader( new InputStreamReader(System.in));
  111. try
  112. {
  113. int n=reader.read();
  114. n=Integer.parseInt(Character.toString(( char )n));
  115. return n;
  116. } catch (Exceptione)
  117. {
  118. throw new RuntimeException();
  119. }
  120. }
  121. public static StringreadLine(Stringpropt)
  122. {
  123. System.out.println(propt);
  124. BufferedReaderreader= new BufferedReader( new InputStreamReader(System.in));
  125. try {
  126. return reader.readLine();
  127. } catch (Exceptione)
  128. {
  129. throw new RuntimeException();
  130. }
  131. }
  132. }

Compass入门指南(二)


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论