lucene + spring

来源:互联网 发布:粉底液推荐知乎 编辑:程序博客网 时间:2024/05/16 02:48

目录结果


一,lucene的索引工具类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.hwt.lucene.index;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.List;  
  6.   
  7. import net.paoding.analysis.analyzer.PaodingAnalyzer;  
  8.   
  9. import org.apache.lucene.analysis.Analyzer;  
  10. import org.apache.lucene.document.Document;  
  11. import org.apache.lucene.document.Field;  
  12. import org.apache.lucene.index.CorruptIndexException;  
  13. import org.apache.lucene.index.IndexReader;  
  14. import org.apache.lucene.index.IndexWriter;  
  15. import org.apache.lucene.index.IndexWriterConfig;  
  16. import org.apache.lucene.index.Term;  
  17. import org.apache.lucene.search.IndexSearcher;  
  18. import org.apache.lucene.store.Directory;  
  19. import org.apache.lucene.store.FSDirectory;  
  20. import org.apache.lucene.store.LockObtainFailedException;  
  21. import org.apache.lucene.util.Version;  
  22.   
  23. /** 
  24.  * lucene的索引工具类 
  25.  *  
  26.  * @author 黄文韬 
  27.  *  
  28.  */  
  29. public class IndexUtils {  
  30.     // 庖丁解牛分词器(单例)  
  31.     private static Analyzer ANALYZER = new PaodingAnalyzer();  
  32.     // 索引的路径  
  33.     private static final String indexPath = "WebRoot/lucene/index";  
  34.   
  35.     /** 
  36.      * 得到庖丁解牛分词器 
  37.      *  
  38.      * @return 
  39.      */  
  40.     public static Analyzer getAnalyzer() {  
  41.         return ANALYZER;  
  42.     }  
  43.   
  44.     /** 
  45.      * 得到路径对象 
  46.      *  
  47.      * @param path 相对路径 
  48.      * @return 
  49.      */  
  50.     public static Directory getDirectory(String path) {  
  51.         Directory directory = null;  
  52.         try {  
  53.             directory = FSDirectory.open(new File(path));  
  54.         } catch (IOException e) {  
  55.             e.printStackTrace();  
  56.         }  
  57.         return directory;  
  58.     }  
  59.   
  60.     /** 
  61.      * 得到读索引类 
  62.      * @return 
  63.      */  
  64.     public static IndexReader getIndexReader() {  
  65.         IndexReader reader = null;  
  66.         try {  
  67.             reader = IndexReader.open(getDirectory(indexPath));  
  68.         } catch (CorruptIndexException e) {  
  69.             e.printStackTrace();  
  70.         } catch (IOException e) {  
  71.             e.printStackTrace();  
  72.         }  
  73.         return reader;  
  74.     }  
  75.   
  76.     /** 
  77.      * 得到些索引类 
  78.      * @return 
  79.      */  
  80.     public static IndexWriter getIndexWriter() {  
  81.         IndexWriter writer = null;  
  82.         try {  
  83.             writer = new IndexWriter(getDirectory(indexPath),  
  84.                     new IndexWriterConfig(Version.LUCENE_36, ANALYZER));  
  85.         } catch (CorruptIndexException e) {  
  86.             e.printStackTrace();  
  87.         } catch (LockObtainFailedException e) {  
  88.             e.printStackTrace();  
  89.         } catch (IOException e) {  
  90.             e.printStackTrace();  
  91.         }  
  92.         return writer;  
  93.     }  
  94.   
  95.     /** 
  96.      * 得到索引搜索类 
  97.      * @return 
  98.      */  
  99.     public static IndexSearcher getIndexSearcher() {  
  100.         IndexSearcher searcher = null;  
  101.         try {  
  102.             searcher = new IndexSearcher(getIndexReader());  
  103.         } catch (Exception e) {  
  104.             e.printStackTrace();  
  105.         }  
  106.         return searcher;  
  107.     }  
  108.   
  109.     /** 
  110.      * 创建索引 
  111.      *  
  112.      * @param result 
  113.      */  
  114.     public static void createIndex(List<IndexField> result) {  
  115.         // 得到输出索引类  
  116.         IndexWriter indexWriter = null;  
  117.         // 索引类  
  118.         try {  
  119.             indexWriter = getIndexWriter();  
  120.             Document doc = new Document();  
  121.             for (IndexField findx : result) {  
  122.                 // 是否存储:Store.YES/Store.NO  
  123.                 // 是否分词:  
  124.                 // Index.ANALYZED/Index.NOT_ANALYZED/Index.NO/Index.ANALYZED_NO_NORMS  
  125.                 doc.add(new Field(findx.getFieldName(), findx.getFieldValue(),  
  126.                         findx.getFieldStore(), findx.getFieldAnalyzed()));  
  127.             }  
  128.             indexWriter.addDocument(doc);  
  129.         } catch (CorruptIndexException e) {  
  130.             e.printStackTrace();  
  131.         } catch (IOException e) {  
  132.             e.printStackTrace();  
  133.         } finally {  
  134.             try {  
  135.                 // 关闭writer  
  136.                 indexWriter.close();  
  137.             } catch (CorruptIndexException e) {  
  138.                 e.printStackTrace();  
  139.             } catch (IOException e) {  
  140.                 e.printStackTrace();  
  141.             }  
  142.         }  
  143.     }  
  144.   
  145.     /** 
  146.      * 优化索引 
  147.      */  
  148.     public static void mergeIndex() {  
  149.         IndexWriter indexWriter = null;  
  150.         // 强制优化索引  
  151.         try {  
  152.             indexWriter = getIndexWriter();  
  153.             indexWriter.forceMerge(1);  
  154.         } catch (CorruptIndexException e) {  
  155.             e.printStackTrace();  
  156.         } catch (IOException e) {  
  157.             e.printStackTrace();  
  158.         } finally {  
  159.             try {  
  160.                 indexWriter.close();  
  161.             } catch (CorruptIndexException e) {  
  162.                 e.printStackTrace();  
  163.             } catch (IOException e) {  
  164.                 e.printStackTrace();  
  165.             }  
  166.         }  
  167.     }  
  168.   
  169.     /** 
  170.      * 更新所有 
  171.      * @param fields 新的document字段信息 
  172.      * @param term 需要替换的查找条件 
  173.      */  
  174.     public static void updateIndex(List<IndexField> fields, Term term) {  
  175.         // 得到输出索引类  
  176.         IndexWriter indexWriter = null;  
  177.         // 索引类  
  178.         try {  
  179.             indexWriter = getIndexWriter();  
  180.             Document doc = new Document();  
  181.             // 是否存储:Store.YES/Store.NO  
  182.             // 是否分词:  
  183.             // Index.ANALYZED/Index.NOT_ANALYZED/Index.NO/Index.ANALYZED_NO_NORMS  
  184.             for (IndexField field : fields) {  
  185.                 doc.add(new Field(field.getFieldName(), field.getFieldValue(),  
  186.                         field.getFieldStore(), field.getFieldAnalyzed()));  
  187.             }  
  188.             indexWriter.updateDocument(term, doc, ANALYZER);  
  189.             indexWriter.forceMerge(1);  
  190.         } catch (CorruptIndexException e) {  
  191.             e.printStackTrace();  
  192.         } catch (IOException e) {  
  193.             e.printStackTrace();  
  194.         } finally {  
  195.             try {  
  196.                 // 关闭writer  
  197.                 indexWriter.close();  
  198.             } catch (CorruptIndexException e) {  
  199.                 e.printStackTrace();  
  200.             } catch (IOException e) {  
  201.                 e.printStackTrace();  
  202.             }  
  203.         }  
  204.     }  
  205.   
  206.     /** 
  207.      * 删除全部索引文件 
  208.      */  
  209.     public static void deleteAll() {  
  210.         IndexWriter writer = null;  
  211.         try {  
  212.             writer = getIndexWriter();  
  213.             writer.deleteAll();  
  214.         } catch (IOException e) {  
  215.             e.printStackTrace();  
  216.         } finally {  
  217.             try {  
  218.                 writer.close();  
  219.             } catch (CorruptIndexException e) {  
  220.                 e.printStackTrace();  
  221.             } catch (IOException e) {  
  222.                 e.printStackTrace();  
  223.             }  
  224.         }  
  225.     }  
  226.   
  227.     /** 
  228.      * 根据条件删除索引 
  229.      * @param term 条件 
  230.      */  
  231.     public static void delete(Term term) {  
  232.         IndexWriter writer = null;  
  233.         IndexReader reader = getIndexReader();  
  234.         try {  
  235.             writer = getIndexWriter();  
  236.             writer.deleteDocuments(term);  
  237.             writer.forceMerge(1);  
  238.         } catch (IOException e) {  
  239.             e.printStackTrace();  
  240.         } finally {  
  241.             try {  
  242.                 writer.close();  
  243.             } catch (CorruptIndexException e) {  
  244.                 e.printStackTrace();  
  245.             } catch (IOException e) {  
  246.                 e.printStackTrace();  
  247.             }  
  248.         }  
  249.     }  
  250.   
  251. }  

二,文件类型的搜索

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.hwt.lucene.index;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9.   
  10. import org.apache.lucene.document.Document;  
  11. import org.apache.lucene.document.Field;  
  12. import org.apache.lucene.document.Field.Index;  
  13. import org.apache.lucene.document.Field.Store;  
  14.   
  15. /** 
  16.  * 文件类型的搜索 
  17.  * @author 黄文韬 
  18.  * 
  19.  */  
  20. public class FileDocument {  
  21.       
  22.     /** 
  23.      * 将文件转换为一个document对象 
  24.      * @param file 文件 
  25.      * @return 
  26.      */  
  27.     public Document fileToDocument(File file){  
  28.         Document document=new Document();  
  29.         document.add(new Field("name", file.getName(), Store.YES, Index.ANALYZED));  
  30.         document.add(new Field("content"this.readFileRetStr(file), Store.YES, Index.ANALYZED));  
  31.         return document;  
  32.     }  
  33.       
  34.     /** 
  35.      * 将名字、内容字段转为document 
  36.      * @param content  内容 
  37.      * @param name 文件名字 
  38.      * @return 
  39.      */  
  40.     public Document stringToDocumet(String name,String content){  
  41.         Document document=new Document();  
  42.         document.add(new Field("name",name, Store.YES, Index.ANALYZED));  
  43.         document.add(new Field("content", content, Store.YES, Index.ANALYZED));  
  44.         return document;  
  45.     }  
  46.       
  47.     /** 
  48.      * 将文件内容转为string类型 
  49.      * @param file 文件 
  50.      * @return 
  51.      */  
  52.     public String readFileRetStr(File file){  
  53.         FileInputStream fStream = null;  
  54.         String tempStr = "";  
  55.         StringBuffer sBuffer = new StringBuffer();  
  56.         try {  
  57.             fStream = new FileInputStream(file);  
  58.             BufferedReader bReader=new BufferedReader(new InputStreamReader(fStream,"UTF-8"));  
  59.             while((tempStr=bReader.readLine())!=null){  
  60.                 sBuffer.append(tempStr);  
  61.             }  
  62.         } catch (FileNotFoundException e) {  
  63.             e.printStackTrace();  
  64.         } catch (IOException e) {  
  65.             e.printStackTrace();  
  66.         } finally {  
  67.             try {  
  68.                 fStream.close();  
  69.             } catch (IOException e) {  
  70.                 e.printStackTrace();  
  71.             }  
  72.         }  
  73.         return sBuffer.toString();  
  74.     }  
  75. }  


三,封装索引字段类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.hwt.lucene.index;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import org.apache.lucene.document.Field.Index;  
  6. import org.apache.lucene.document.Field.Store;  
  7.   
  8. /** 
  9.  * 封装索引字段类 
  10.  * @author hwt 
  11.  * 
  12.  */  
  13. public class IndexField implements Serializable{  
  14.     private String fieldName;  
  15.     private String fieldValue;  
  16.     private Store fieldStore;//是否存储:Store.YES/Store.NO   
  17.     private Index fieldAnalyzed;//是否分词: Index.ANALYZED/Index.NOT_ANALYZED/Index.NO/Index.ANALYZED_NO_NORMS  
  18.       
  19.     public String getFieldName() {  
  20.         return fieldName;  
  21.     }  
  22.     public void setFieldName(String fieldName) {  
  23.         this.fieldName = fieldName;  
  24.     }  
  25.     public String getFieldValue() {  
  26.         return fieldValue;  
  27.     }  
  28.     public void setFieldValue(String fieldValue) {  
  29.         this.fieldValue = fieldValue;  
  30.     }  
  31.     public Store getFieldStore() {  
  32.         return fieldStore;  
  33.     }  
  34.     public void setFieldStore(Store fieldStore) {  
  35.         this.fieldStore = fieldStore;  
  36.     }  
  37.     public Index getFieldAnalyzed() {  
  38.         return fieldAnalyzed;  
  39.     }  
  40.     public void setFieldAnalyzed(Index fieldAnalyzed) {  
  41.         this.fieldAnalyzed = fieldAnalyzed;  
  42.     }  
  43.       
  44. }  

四,分页缓存类

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package com.hwt.lucene.index;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import org.apache.log4j.Logger;  
  10. import org.apache.lucene.document.Document;  
  11. import org.apache.lucene.search.IndexSearcher;  
  12. import org.apache.lucene.search.Query;  
  13. import org.apache.lucene.search.ScoreDoc;  
  14. import org.apache.lucene.search.Sort;  
  15. import org.apache.lucene.search.TopDocs;  
  16.   
  17. public class CachePage {  
  18.     private static final Logger LOGGER = Logger.getLogger(CachePage.class);  
  19.     private int pageStart = 1// 页码  
  20.     private int pageSize = 15// 每页显示的大小  
  21.     private int pageNum = 0;  //总页数  
  22.     private int totalNum = 0//总记录条数  
  23.     private int cacheSize = 100// 缓存大小  
  24.     private List<Document> cacheList = new ArrayList<Document>(); // 缓存列表  
  25.       
  26.     /** 
  27.      * 构造方法 
  28.      * @param pageSize 每页大小 
  29.      * @param cacheSize 缓存大小 
  30.      */  
  31.     public CachePage(Integer pageSize, Integer cacheSize) {  
  32.         this.pageSize = pageSize;  
  33.         if (cacheSize != null) {  
  34.             this.cacheSize = cacheSize;  
  35.         }  
  36.     }  
  37.   
  38.     /** 
  39.      * 判断是否存在缓存中 
  40.      *  
  41.      * @param page 
  42.      *            页码 
  43.      * @return 
  44.      */  
  45.     public boolean inCache(int page) {  
  46.         // 当前缓存对象的个数  
  47.        int cacheNum = cacheList.size();  
  48.        if (cacheNum > 0) {  
  49.             if (page <= 0) {  
  50.                 page = 1;  
  51.             }  
  52.             // 判断当前页是不是在缓存中  
  53.             if (page >= pageStart && (page - pageStart) * pageSize <= cacheNum) {  
  54.                 return true;  
  55.             } else {  
  56.                 return false;  
  57.             }  
  58.         }else {  
  59.             return false;  
  60.         }  
  61.     }  
  62.   
  63.     /** 
  64.      * 清空缓存 
  65.      * @param pageNum 起始页 
  66.      */  
  67.     public void refleshCache() {  
  68. //      this.isFirst = true;  
  69.         for (int i = cacheList.size() -1 ; i  >= 0; i--) {  
  70.             cacheList.remove(i);  
  71.         }  
  72.     }  
  73.   
  74.     /** 
  75.      * 新增缓存 
  76.      *  
  77.      * @param doc 
  78.      */  
  79.     public void addCache(Document doc) {  
  80.         if (this.cacheList.size() < cacheSize) {  
  81.             this.cacheList.add(doc);  
  82.         } else {  
  83.             LOGGER.info("缓存池已满");  
  84.         }  
  85.     }  
  86.       
  87.     /** 
  88.      * 读缓存中的数据 
  89.      * @param page 
  90.      * @return 
  91.      */  
  92.     public Map readCache(int page) {  
  93.         // 判断是否存在于缓存池中  
  94.         int start = (page - pageStart) * pageSize;  
  95.         int end = start + pageSize > cacheList.size() ? cacheList.size()  
  96.                 : start + pageSize;  
  97.         //缓存中的结果集  
  98.         List<Document> cacheRs = new ArrayList<Document>();  
  99.         for (int i = start; i < end; i++) {  
  100.             cacheRs.add(cacheList.get(i));  
  101.         }  
  102.           
  103.         //缓存结果集  
  104.         Map resultMap = new HashMap();  
  105.         resultMap.put("currentPage", page); //当前页  
  106.         resultMap.put("totalNum", totalNum); //总记录条数  
  107.         resultMap.put("pageNum", pageNum); //总页数  
  108.         resultMap.put("list", cacheRs);  
  109.           
  110.         return resultMap;  
  111.     }  
  112.       
  113.     /** 
  114.      * 搜索 
  115.      * @param query query对象 
  116.      * @param sort 排序对象 
  117.      * @param page 页码 
  118.      * @return 
  119.      */  
  120.     public Map search(Query query,Sort sort,int page){  
  121.         if (page < 0) {  
  122.             page = 1;  
  123.         }  
  124.         //如果存在缓存中  
  125.         if (inCache(page)) {  
  126.             return readCache(page);  
  127.         }else {//如果不在缓存中  
  128.             IndexSearcher searcher = IndexUtils.getIndexSearcher();  
  129.             try {  
  130.                 //显示条数  
  131.                 int querySize = (page*pageSize / cacheSize + 1 )*100;  
  132.                 //设置查询、查询显示的条数、排序对象  
  133.                 TopDocs topDocs = searcher.search(query, querySize , sort);  
  134.                   
  135.                 //总共记录条数  
  136.                 int totalNum = topDocs.totalHits;  
  137.                 int pageNum = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;  
  138.                   
  139.                 if (page > pageNum) {  
  140.                     page = pageNum;  
  141.                 }  
  142.                   
  143.                 //得到记录集  
  144.                 ScoreDoc[] docs = topDocs.scoreDocs;  
  145.                   
  146.                 //保存当前页的前后两页放入缓存中  
  147.                 int startPage = 1;  
  148.                 int endPage   = 1;  
  149.                 if (page < 3) { //前五页  
  150.                     startPage = 1;  
  151.                     endPage = startPage + 4 > pageNum ? pageNum : startPage + 4;  
  152.                 }else if(page > pageNum - 2){ //后五页  
  153.                     endPage = pageNum ;  
  154.                     startPage = endPage - 4 < 0 ? 1 : endPage - 4;  
  155.                 } else { //中间页  
  156.                     startPage = page - 2 <= 0 ? 1 : page - 2;  
  157.                     endPage   = page + 2 > pageNum ? pageNum : page + 2;  
  158.                 }  
  159.                   
  160.                 //清空缓存  
  161.                 refleshCache();  
  162.                   
  163.                 int startSize = (startPage - 1)*pageSize ;  
  164.                 int endSize = startSize + cacheSize > totalNum ? totalNum : startSize + cacheSize ;  
  165.                   
  166.                 //将对象加入缓存中  
  167.                 for (int i = startSize ; i < endSize; i++) {  
  168.                     Document doc = searcher.doc(docs[i].doc);  
  169.                     addCache(doc);  
  170.                 }  
  171.                   
  172.                 //替换缓存集合  
  173.                 this.pageNum = pageNum;  
  174.                 this.totalNum = totalNum;  
  175.                 this.pageStart = startPage;  
  176.                   
  177.                 return readCache(page);  
  178.                   
  179.             } catch (IOException e) {  
  180.                 e.printStackTrace();  
  181.                 return null;  
  182.             }  
  183.         }  
  184.     }  
  185.   
  186.     public Integer getPageSize() {  
  187.         return pageSize;  
  188.     }  
  189.   
  190.     public void setPageSize(Integer pageSize) {  
  191.         this.pageSize = pageSize;  
  192.     }  
  193.   
  194.     public Integer getPageStart() {  
  195.         return pageStart;  
  196.     }  
  197.   
  198.     public void setPageStart(Integer pageStart) {  
  199.         this.pageStart = pageStart;  
  200.     }  
  201.   
  202.     public Integer getCacheSize() {  
  203.         return cacheSize;  
  204.     }  
  205.   
  206.     public void setCacheSize(Integer cacheSize) {  
  207.         this.cacheSize = cacheSize;  
  208.     }  
  209.   
  210.     public List<Document> getCacheList() {  
  211.         return cacheList;  
  212.     }  
  213.   
  214.     public void setCacheList(List<Document> cacheList) {  
  215.         this.cacheList = cacheList;  
  216.     }  
  217.       
  218. //  public boolean isFirst() {  
  219. //      return isFirst;  
  220. //  }  
  221. //  
  222. //  public void setFirst(boolean isFirst) {  
  223. //      this.isFirst = isFirst;  
  224. //  }  
  225. }  


测试类:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. package test;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import javax.print.Doc;  
  10.   
  11. import org.apache.lucene.analysis.Analyzer;  
  12. import org.apache.lucene.analysis.cjk.CJKAnalyzer;  
  13. import org.apache.lucene.document.Document;  
  14. import org.apache.lucene.document.Field.Index;  
  15. import org.apache.lucene.document.Field.Store;  
  16. import org.apache.lucene.index.IndexReader;  
  17. import org.apache.lucene.index.Term;  
  18. import org.apache.lucene.queryParser.ParseException;  
  19. import org.apache.lucene.queryParser.QueryParser;  
  20. import org.apache.lucene.search.BooleanClause.Occur;  
  21. import org.apache.lucene.search.BooleanQuery;  
  22. import org.apache.lucene.search.IndexSearcher;  
  23. import org.apache.lucene.search.Query;  
  24. import org.apache.lucene.search.ScoreDoc;  
  25. import org.apache.lucene.search.Searcher;  
  26. import org.apache.lucene.search.Sort;  
  27. import org.apache.lucene.search.SortField;  
  28. import org.apache.lucene.search.TermQuery;  
  29. import org.apache.lucene.search.TopDocs;  
  30. import org.apache.lucene.store.Directory;  
  31. import org.apache.lucene.store.FSDirectory;  
  32. import org.apache.lucene.util.Version;  
  33. import org.springframework.context.ApplicationContext;  
  34. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  35.   
  36. import com.hwt.lucene.index.CachePage;  
  37. import com.hwt.lucene.index.IndexField;  
  38. import com.hwt.lucene.index.IndexUtils;  
  39.   
  40. public class Test {  
  41.       
  42.     public static void main(String[] args) throws IOException, ParseException {  
  43.         List<IndexField> fieldIndexs2 = new ArrayList<IndexField>();  
  44.         IndexField  ind3 = new IndexField();  
  45.         ind3.setFieldName("title");  
  46.         ind3.setFieldValue("美国攻打伊朗");  
  47.         ind3.setFieldStore(Store.YES);  
  48.         ind3.setFieldAnalyzed(Index.ANALYZED);  
  49.         fieldIndexs2.add(ind3);  
  50.   
  51.         IndexField  ind = new IndexField();  
  52.         ind.setFieldName("content");  
  53.         ind.setFieldValue("美国派兵3333,航母出发了,中国航公出发");  
  54.         ind.setFieldStore(Store.YES);  
  55.         ind.setFieldAnalyzed(Index.ANALYZED);  
  56.         fieldIndexs2.add(ind);  
  57.           
  58.         IndexField  ind2 = new IndexField();  
  59.         ind2.setFieldName("Id");  
  60.         ind2.setFieldValue("12");  
  61.         ind2.setFieldStore(Store.YES);  
  62.         ind2.setFieldAnalyzed(Index.NOT_ANALYZED);  
  63.         fieldIndexs2.add(ind2);  
  64.           
  65.         //创建索引  
  66. //      IndexUtils.createIndex(fieldIndexs2);  
  67.         //删除索引  
  68. //      IndexUtils.delete(new Term("Id","2"));  
  69.         //修改索引  
  70. //      IndexUtils.updateIndex(fieldIndexs2, new Term("Id","2"));  
  71.           
  72.           
  73.         Analyzer analyzer = IndexUtils.getAnalyzer();  
  74.         QueryParser titleParser = new QueryParser(Version.LUCENE_36,"title",analyzer);  
  75.         QueryParser contentParser = new QueryParser(Version.LUCENE_36,"content",analyzer);  
  76.           
  77. //      Query contentQuery = new TermQuery(new Term("title","美国"));  
  78.           
  79.         Query titleQuery = titleParser.parse("美国");  
  80.         Query contentQuery = contentParser.parse("美国");  
  81.           
  82.         BooleanQuery query = new BooleanQuery();  
  83.         query.add(titleQuery, Occur.MUST);  
  84.         query.add(contentQuery,Occur.SHOULD);  
  85.           
  86.         IndexSearcher searcher = IndexUtils.getIndexSearcher();  
  87.           
  88.         //排序对象:排序字段,排序字段类型,是否降序(默认false升序)  
  89.         Sort sort = new Sort(new SortField("Id",SortField.INT, true));  
  90.         //对多个字段进行排序  
  91. //      Sort sort = new Sort(new SortField[]{new SortField("Id",SortField.INT, true),  
  92. //      new SortField("title",SortField.INT, true)});  
  93.           
  94.         CachePage cachePage = new CachePage(1100);  
  95.         Map map = cachePage.search(query, sort, 1);  
  96.         System.out.println("起始页:"+ cachePage.getPageStart());  
  97.         System.out.println("总页数:"+map.get("pageNum"));  
  98.         System.out.println("总条数:"+map.get("totalNum"));  
  99.         List<Document> docs = (List<Document>) map.get("list");  
  100.         for (Document document : docs) {  
  101.             System.out.println(document.get("Id"));  
  102.             System.out.println(document.get("title"));  
  103.             System.out.println(document.get("content"));  
  104.         }  
  105.           
  106.         System.out.println("+++++++++++++++++++");  
  107.         cachePage.refleshCache();  
  108. //        
  109.         //查询缓存的  
  110.         Map map2 = cachePage.search(query, sort, 4);  
  111.         System.out.println("起始页:"+ cachePage.getPageStart());  
  112.         System.out.println("总页数:"+map2.get("pageNum"));  
  113.         System.out.println("总条数:"+map2.get("totalNum"));  
  114.         List<Document> docs2 = (List<Document>) map2.get("list");  
  115.         for (Document document : docs2) {  
  116.             System.out.println(document.get("Id"));  
  117.             System.out.println(document.get("title"));  
  118.             System.out.println(document.get("content"));  
  119.         }  
  120. //        
  121. //      System.out.println("+++++++++++++++++++");  
  122. //      Map map3 = cachePage.search(query, sort, 5);  
  123. //      System.out.println("总页数:"+map3.get("pageNum"));  
  124. //      System.out.println("总条数:"+map3.get("totalNum"));  
  125. //      List<Document> docs4 = (List<Document>) map3.get("list");  
  126. //      for (Document document : docs4) {  
  127. //          System.out.println(document.get("Id"));  
  128. //          System.out.println(document.get("title"));  
  129. //          System.out.println(document.get("content"));  
  130. //      }  
  131.           
  132.         //对对个字段进行排序  
  133. //      Sort sort = new Sort(new SortField[]{new SortField("Id",SortField.STRING, true),  
  134. //                    new SortField("title",SortField.STRING, true)});  
  135. //      TopDocs docs = searcher.search(query,100,sort); //返回前100条记录  
  136.   
  137. //      docs.totalHits是所有的记录条数,与上面设置的100无关  
  138.           
  139. //      System.out.println("共找到"+docs.totalHits+"条记录");  
  140. //        
  141. //      ScoreDoc[] scoreDocs = docs.scoreDocs;  
  142. //  
  143. //        for (int i = 0,len = scoreDocs.length ; i < len; i++) {  
  144. //          System.out.println(scoreDocs[i].doc);  
  145. //      }  
  146. //      for (ScoreDoc scoreDoc : scoreDocs) {  
  147. //          int docid = scoreDoc.doc;  
  148. //          Document document = searcher.doc(docid);  
  149. //          System.out.println(document.get("Id"));  
  150. //          System.out.println(document.get("title"));  
  151. //          System.out.println(document.get("content"));  
  152. //          System.out.println("===============================");  
  153. //      }  
  154.           
  155. //      IndexSearcher indexSearcher = IndexUtils.getIndexSearcher();  
  156. //  
  157. //      TopDocs topDocs = indexSearcher.search(query, 10);  
  158. //  
  159. //      ScoreDoc[] docs = topDocs.scoreDocs;  
  160. //      System.out.println("共找到:"+docs.length);  
  161.   
  162. //      for (ScoreDoc scoreDoc : docs) {  
  163. //          int docid = scoreDoc.doc;  
  164. //          Document document = indexSearcher.doc(docid);  
  165. //          System.out.println(document.get("Id"));  
  166. //          System.out.println(document.get("title"));  
  167. //          System.out.println(document.get("content"));  
  168. //          System.out.println("===============================");  
  169. //      }  
  170. //        
  171. //  }  
  172.           
  173.           
  174.           
  175. //      IndexUtils.deleteAll();  
  176.     }  
  177. }  

0 0
原创粉丝点击