标签:
  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的实现机制是一样的,采用的是堆外分配管理内存的方式.不知道说的对不对,求大神指点一下
 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 @Controller
20 @RequestMapping("PollutantwaterController")
21 public class PollutantwaterController {
22  
23  
24     @Resource
25     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 }
<%@ 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.autocompl
ete.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使用这个插件可以明显看到下拉提示;
标签:
原文地址:http://www.cnblogs.com/xbgfy/p/5725597.html