- lucene他只是一個外掛程式,一般使用是嵌套在項目裡面的.直接看代碼
- 需要的jar包分詞工具很多選擇一個支援中文的即可
- 工具類代碼
1 package com.chn.supervision.util; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.ArrayList; 6 import java.util.HashMap; 7 import java.util.List; 8 import java.util.Map; 9 10 import org.apache.commons.lang3.StringUtils; 11 import org.apache.lucene.analysis.Analyzer; 12 import org.apache.lucene.analysis.standard.StandardAnalyzer; 13 import org.apache.lucene.document.Document; 14 import org.apache.lucene.document.Field; 15 import org.apache.lucene.document.TextField; 16 import org.apache.lucene.index.DirectoryReader; 17 import org.apache.lucene.index.IndexWriter; 18 import org.apache.lucene.index.IndexWriterConfig; 19 import org.apache.lucene.queryparser.classic.ParseException; 20 import org.apache.lucene.queryparser.classic.QueryParser; 21 import org.apache.lucene.search.IndexSearcher; 22 import org.apache.lucene.search.Query; 23 import org.apache.lucene.search.ScoreDoc; 24 import org.apache.lucene.store.Directory; 25 import org.apache.lucene.store.FSDirectory; 26 import org.apache.lucene.util.Version; 27 import org.wltea.analyzer.lucene.IKAnalyzer; 28 29 import com.chn.supervision.vo.Pollutantwater; 30 31 /** 32 * 33 * @author moon 34 * 35 */ 36 public class LuceneUtil { 37 private static String searchDir = "E:\\Test\\Index"; 38 private static File indexFile = null; 39 private static Analyzer analyzer = null; 40 /** 索引頁面緩衝 */ 41 private int maxBufferedDocs = 500; 42 43 /** 44 * 傳遞集合對象,並且建立索引,返回索引資料 45 * 46 * @param list 47 */ 48 public static void sreachDatas(List<Map> list) { 49 createIndex(list); 50 } 51 52 /** 53 * 為資料庫檢索資料建立索引,並且這個地方需要定時調用並且建立 54 * 55 * @param list 56 */ 57 private static void createIndex(List<Map> list) { 58 // 儲存到記憶體裡面 59 // Directory directory = new RAMDirectory(); 60 // 判斷是否存在目前的目錄,並且建立 61 try { 62 Directory directory = FSDirectory.open(FileUtil 63 .createFileDir(searchDir)); 64 analyzer = new IKAnalyzer(); 65 // 建立IndexWriter,進行索引檔案的寫入。 66 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, 67 analyzer); 68 IndexWriter iwriter = new IndexWriter(directory, config); 69 Document doc = null; 70 int length = list.size(); 71 for (int i = 0; i < length; i++) { 72 doc = new Document();// 建立文檔 73 String address = ""; 74 // 對文檔地址建立索引 75 Map map=(Map) list.get(i); 76 if (StringUtils.isNotBlank(map.get("address").toString())) { 77 address =map.get("address").toString(); 78 } 79 doc.add(new Field("address", address, TextField.TYPE_STORED)); 80 iwriter.addDocument(doc);// 添加到文檔 81 } 82 iwriter.close(); 83 84 } catch (IOException e) { 85 e.printStackTrace(); 86 } 87 } 88 89 /** 90 * 根據查詢字串檢索內容,返回查詢集合 91 * 92 * @param str 93 */ 94 public static List sreach(String str) { 95 List<Map> list = new ArrayList<Map>(); 96 Directory directory; 97 try { 98 directory = FSDirectory.open(new File(searchDir)); 99 DirectoryReader ireader = DirectoryReader.open(directory);100 IndexSearcher isearcher = new IndexSearcher(ireader);101 QueryParser parser = new QueryParser(Version.LUCENE_40, "address",102 new StandardAnalyzer(Version.LUCENE_40));103 Query query;104 try {105 query = parser.parse(str);106 //第一個事查詢,第二個是過濾條件,第三個是查詢個數,預設匹配度高的顯示在前面107 ScoreDoc[] hits = isearcher.search(query, null, 10).scoreDocs;108 for (int i = 0; i < hits.length; i++) {109 Document hitDoc = isearcher.doc(hits[i].doc);110 System.out.println(hitDoc.get("address").toString());111 Map map=new HashMap();112 map.put("address", hitDoc.get("address").toString());113 list.add(map);114 }115 ireader.close();116 directory.close();117 } catch (ParseException e) {118 e.printStackTrace();119 }120 121 } catch (IOException e) {122 e.printStackTrace();123 }124 return list;125 }126 127 }
這個地方有個問題.不知道大家是否關心過這個問題,在選擇索引是記憶體儲存還是磁碟儲存的時候,到底哪個更加合理的問題;本菜鳥覺得還是儲存在磁碟上面好.原因如下,Lucene的索引儲存使用的記憶體也是jvm分配的,這樣一來存在記憶體回收的問題,那麼也就是只有被回收了,那麼這個索引還是需要重新建立,在儲存到記憶體;重新建立索引是很耗費時間空間的.其實這個問題困擾我很久,後來發現他應該是和nio的實現機制是一樣的,採用的是堆外分配管理記憶體的方式.不知道說的對不對,求大神指點一下
- controllers代碼:
1 package com.chn.supervision.controllers; 2 3 import java.io.PrintWriter; 4 import java.util.List; 5 import java.util.Map; 6 7 import javax.annotation.Resource; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse;10 11 import org.springframework.stereotype.Controller;12 import org.springframework.web.bind.annotation.RequestMapping;13 14 import com.chn.supervision.service.IPollutantwaterService;15 import com.chn.supervision.util.JsonUtil;16 import com.chn.supervision.util.LuceneUtil;17 import com.chn.supervision.vo.Pollutantwater;18 19 @Controller20 @RequestMapping("PollutantwaterController")21 public class PollutantwaterController {22 23 24 @Resource25 IPollutantwaterService pollutantwaterService;26 @RequestMapping("/sreachAddressList")27 public void sreachAddressList(HttpServletRequest request,28 HttpServletResponse response,PrintWriter pw){29 String address=request.getParameter("v");30 List<Map> map=pollutantwaterService.getListBySQL(null);//擷取資料集合31 //LuceneUtil.sreachDatas(map);//初始化索引32 List list= LuceneUtil.sreach(address);33 String json= JsonUtil.jsonArray(list, new String[]{}, null);34 //System.out.println("+++++++"+list);35 pw.print(json);36 pw.close();37 }38 39 40 }
- jsp代碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP ‘index.jsp‘ starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><style type="text/css">input{ width: 500px; height: 35px; font-size: 18px; margin-left: 150px; margin-top: 20px; } </style><link rel="stylesheet" href="js_plugin/jquery.autocomplete/jquery.autocomplete.css" type="text/css"></head><body> <div style="margin: 0 auto;width: 800px;height: 500px;"> <input placeholder="請輸入條件" id="search" name="search" autocomplete="off"> </div> </body><script type="text/javascript" src="js_plugin/jquery-1.7.min.js"></script><script src="js_plugin/jquery.autocomplete/jquery.autocomplete.js"></script><script src="js_plugin/jquery.placeholder.min.js"></script><script> $(function(){ $("#search").placeholder(); }) $("#search").autocomplete("PollutantwaterController/sreachAddressList", { width : 500, scroll : true, matchCase:false, matchContains :true, scrollHeight : 400, extraParams:{v:function() { return $(‘#search‘).val();}}, parse: function(data) { console.log("+++++++++++"+data); return $.map(eval(data), function(row) { return { data: row, value: row.address, //此處無需把全部列列出來,只是兩個關鍵列 result: row.address } }); }, formatItem : function(row, i, max) { //彈出下拉顯示文本地區,格式可以自訂 return row.address +"<span style=‘float: right;color: red‘>測試資料</span>"; }, formatResult : function(row, i, max) { //單擊確認的時候,給文字框賦值 return row.address ; }, formatMatch : function(row, i, max) { return row.address ; } });</script></html>
autocomplete使用這個外掛程式可以明顯看到下拉提示;