lucene4.7(3) 全文檢索之 相關類
阿新 • • 發佈:2019-02-07
public class DBIndex{ public static final config _$=new config(); public static class config{ public static final Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_47);//分詞器 public String CLASS_PATH= Config.CLASS_PATH; public config(){ } public String getDatePath() { return CLASS_PATH+"query/index"; } public File getDataFile(){ return new File(getDatePath()); } public String getIndexPath() { return CLASS_PATH+"query/index"; } public File getIndexFile(){ return new File(getIndexPath()); } /** * 將字串中HTML標記清空 * @param msg * @return String */ public String clearHTMLToString(String msg){ if(StringUtils.isEmpty(msg)){ return ""; } return msg.replaceAll("(?is)<(.*?)>","").replaceAll("\\s*|\t|\r|\n",""); } /**將查詢出的Map物件,轉換為Lucene中的Document物件。 * @param news * @return org.apache.lucene.document.Document * */ public void toDocument(IndexWriter iw,Map<String,Object> news)throws Exception{ Document doc = new Document(); Iterator iter = news.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val=entry.getValue()==null?"":entry.getValue(); if("FILE_NAME".equals(key.toString().toUpperCase())){ List file=UpInfoService.toMapList(String.valueOf(val)); String textString=""; for(int i=0;i<file.size();i++){ Map map=(Map)file.get(i); textString+=map.get("description").toString(); } val=textString; }else if(val instanceof Date){ doc.add(new StringField(key.toString(),WebUtil.getDate((Date)val,"yyyy-MM-dd HH:mm:ss"), Field.Store.YES));//標題 }else{ doc.add(new StringField(key.toString(),clearHTMLToString(String.valueOf(val)), Field.Store.YES)); } } iw.addDocument(doc); } /** * 讀取檔案內容為String * @param file * @return String */ public String readFileContent(File file) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); StringBuffer content = new StringBuffer(); for (String line = null; (line = reader.readLine()) != null;) { content.append(line).append("\n"); } return content.toString(); } catch (Exception e) { throw new RuntimeException(e); } } public boolean isEmpty(Object obj){ if(obj==null){ return true; } return "".equals(obj.toString()); } public boolean is(String filed,String ...filds){ for (String string : filds) { if(filed.equalsIgnoreCase(string)){ return true; } } return false; } }