使用Lucene做商品搜索

前提:

在现有的代码上做的修改,只做了少量重构,程序结构不一定合理,仅做为demo使用。

需求:后台需要通过商品的名称、描述、商家名称、电话等方式查找商品列表

方案:Lucene+MySQL

架构:

一个Timer,每一段时间从数据库中取一次数据加载到Lucene中。由于需要增量更新,所以在磁盘中记录导入的广告最大ID值,以后只插入大于ID的数据

搜索时,先通过关键字上Lucene中搜索到对应的商品ID集合,再通过ID集合从MySQL中查询对应的列表信息

Lucene操作接口(LuceneService.java):

 1 /*
 2  * Lucene操作类
 3  * */
 4 package cn.springmvc.service.common;
 5 
 6 
 7 import java.util.HashMap;
 8 import java.util.List;
 9 
10 import cn.springmvc.model.postermanager.SearchBean;
11 
12 public interface LuceneService {
13     
14 /**
15  * 创建Lucene索引
16  * @param indexType 索引类型,区分不同的业务索引
17  * @param indexKey    索引存储的key名称
18  * @param indexValue    索引存储的value名称
19  * @param hs    待缓存数据集
20  * @return
21  */
22 public void createIndex(String indexType,String indexKey,String indexValue,HashMap<String, String> hs);
23 
24 /**
25  * 通过关键字查询
26  * @param indexType    索引类型,区分不同的业务索引
27  * @param indexKey
28  * @param indexValue
29  * @param queryStr    查找关键字
30  * @return
31  */
32 public List<SearchBean> search(String indexType,String indexKey, String indexValue,String queryStr); 
33 
34 }

Lucene具体实现类

  1 /**
  2  * 
  3  */
  4 package cn.springmvc.service.common;
  5 
  6 import java.io.BufferedReader;
  7 import java.io.File;
  8 import java.io.FileReader;
  9 import java.io.FileWriter;
 10 import java.io.IOException;
 11 import java.io.PrintWriter;
 12 import java.nio.file.Path;
 13 import java.nio.file.Paths;
 14 import java.util.ArrayList;
 15 import java.util.HashMap;
 16 import java.util.Iterator;
 17 import java.util.List;
 18 import java.util.Map.Entry;
 19 
 20 import org.apache.lucene.analysis.Analyzer;
 21 import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
 22 import org.apache.lucene.document.Document;
 23 import org.apache.lucene.document.Field;
 24 import org.apache.lucene.document.TextField;
 25 import org.apache.lucene.index.DirectoryReader;
 26 import org.apache.lucene.index.IndexWriter;
 27 import org.apache.lucene.index.IndexWriterConfig;
 28 import org.apache.lucene.queryparser.classic.QueryParser;
 29 import org.apache.lucene.search.IndexSearcher;
 30 import org.apache.lucene.search.Query;
 31 import org.apache.lucene.search.ScoreDoc;
 32 import org.apache.lucene.search.TopScoreDocCollector;
 33 import org.apache.lucene.store.Directory;
 34 import org.apache.lucene.store.FSDirectory;
 35 
 36 import cn.springmvc.model.postermanager.SearchBean;
 37 
 38 /**
 39  * @author 1
 40  *
 41  */
 42 public class LuceneServiceImpl implements LuceneService {
 43 
 44     private Directory directory;
 45     private IndexWriter indexWriter;
 46     private IndexSearcher isearcher;
 47     private DirectoryReader ireader;
 48     private Path indexFilePath;
 49     private static final String BASE_PATH = "/tmp/lucene/";
 50     private File indexFile;
 51     private Analyzer analyzer;
 52 
 53     private void AddDocument(String indexType, String indexKey,
 54             String indexValue, HashMap<String, String> hs, IndexWriter iWriter) {
 55         Document doc;
 56         Iterator<Entry<String, String>> itor = hs.entrySet().iterator();
 57 
 58         while (itor.hasNext()) {
 59             doc = new Document();
 60             Entry<String, String> entry = itor.next();
 61             doc.add(new Field(indexKey, entry.getKey().toString(),
 62                     TextField.TYPE_STORED));
 63             doc.add(new Field(indexValue, entry.getValue().toString(),
 64                     TextField.TYPE_STORED));
 65             try {
 66                 iWriter.addDocument(doc);
 67             } catch (Exception e) {
 68                 e.printStackTrace();
 69             }
 70         }
 71     }
 72 
 73     // 取得存储在磁盘中的ID
 74     public static String getStoreId(String indexType) {
 75         String path = Paths.get(BASE_PATH + indexType + "/" + "storeid.txt")
 76                 .toString();
 77         String storeId = "";
 78         try {
 79             File file = new File(path);
 80             if (!file.exists()) {
 81                 file.createNewFile();
 82             }
 83             FileReader fr = new FileReader(path);
 84             BufferedReader br = new BufferedReader(fr);
 85             storeId = br.readLine();
 86             if (storeId == null || storeId == "")
 87                 storeId = "0";
 88             br.close();
 89             fr.close();
 90         } catch (Exception e) {
 91             e.printStackTrace();
 92         }
 93         return storeId;
 94     }
 95 
 96     // 将ID写入到磁盘文件中
 97     public static boolean setStoreId(String indexType, String storeId) {
 98         String path = Paths.get(BASE_PATH + indexType + "/" + "storeid.txt")
 99                 .toString();
100         boolean b = false;
101         try {
102             File file = new File(path);
103             if (!file.exists()) {
104                 file.createNewFile();
105             }
106             FileWriter fw = new FileWriter(path);
107             PrintWriter out = new PrintWriter(fw);
108             out.write(storeId);
109             out.close();
110             fw.close();
111             b = true;
112         } catch (IOException e) {
113             e.printStackTrace();
114         }
115         return b;
116     }
117 
118     /**
119      * 创建Lucene索引
120      */
121     @Override
122     public void createIndex(String indexType, String indexKey,
123             String indexValue, HashMap<String, String> hs) {
124         indexFilePath = Paths.get(BASE_PATH + indexType);
125         indexFile = new File(indexFilePath.toString());
126         if (!indexFile.exists()) {
127             indexFile.mkdir();
128         }
129         try {
130             directory = FSDirectory.open(indexFilePath);
131             analyzer = new SmartChineseAnalyzer();
132 
133             IndexWriterConfig config = new IndexWriterConfig(analyzer);
134             config.setCommitOnClose(true);
135 
136             indexWriter = new IndexWriter(directory, config);
137 
138             AddDocument(indexType, indexKey, indexValue, hs, indexWriter);
139 
140             indexWriter.close();
141 
142         } catch (Exception e) {
143             e.printStackTrace();
144         }
145 
146     }
147 
148     /**
149      * 搜索
150      */
151     @Override
152     public List<SearchBean> search(String indexType, String indexKey,
153             String indexValue, String queryStr) {
154 
155         // Path indexFilePath = Paths.get("/tmp/lucene/" + indexType);
156         ScoreDoc[] hits = null;
157         List<SearchBean> listBean = new ArrayList<SearchBean>();
158         SearchBean bean = null;
159         indexFilePath = Paths.get(BASE_PATH + indexType);
160         indexFile = new File(indexFilePath.toString());
161         if (!indexFile.exists()) {
162             indexFile.mkdir();
163         }
164 
165         try {
166             directory = FSDirectory.open(indexFilePath);
167 
168             // Now search the index:
169             ireader = DirectoryReader.open(directory);
170             isearcher = new IndexSearcher(ireader);
171             // Parse a simple query that searches for "text":
172             analyzer = new SmartChineseAnalyzer();
173             QueryParser parser = new QueryParser(indexValue, analyzer);
174             Query query = parser.parse(queryStr);
175             TopScoreDocCollector collector = TopScoreDocCollector.create(1000);
176             isearcher.search(query, collector);
177             hits = collector.topDocs().scoreDocs;
178 
179             for (int i = 0; i < hits.length; i++) {
180                 int docId = hits[i].doc;
181 
182                 Document doc = isearcher.doc(docId);
183                 bean = new SearchBean();
184                 bean.setId(doc.get(indexKey));
185                 bean.setContent(doc.get(indexValue));
186                 listBean.add(bean);
187             }
188 
189             ireader.close();
190             directory.close();
191         } catch (Exception e) {
192             e.printStackTrace();
193         }
194 
195         return listBean;
196     }
197 }
逻辑类
 1     /**
 2      * 给Timmer用的,建议每10分钟更新一次。增量更新,修改不更新,待改进.
 3      */
 4     public void createLuceneIndex() {
 5         // 获取Lucene中广告最大ID值
 6         int addedId = Integer.parseInt(LuceneServiceImpl.getStoreId("posters"));
 7         // 取出数据库中广告相关信息
 8         Posters entity = new Posters();
 9         entity.setId(addedId);
10         // entity.
11         List<Posters> lp = this.postersForLucene("id", "desc", entity);
12         // 拼接数据
13         HashMap<String, String> hs = new HashMap<String, String>();
14         LuceneService luceneService = new LuceneServiceImpl();
15         for (int i = 0; i < lp.size(); i++) {
16             if (i == 0) {
17                 LuceneServiceImpl.setStoreId("posters", lp.get(i).getId()
18                         .toString());
19             }
20             hs.put(lp.get(i).getId().toString(), lp.get(i).getPoster_title()+ " "
21                     + lp.get(i).getCompany_name()+ " "
22                     + lp.get(i).getCompany_describe()+ " "
23                     + lp.get(i).getPoster_describe() + " "
24                     + lp.get(i).getMobile());
25         }
26 
27         // 调用Lucene操作类创建Index
28 
29         luceneService.createIndex("posters", "id", "content", hs);
30     }
31 
32     @Override
33     public List<Posters> search(String sort, String order, String keyWords,
34             Posters entity) {
35 
36         if (keyWords != null && keyWords != "") {
37             // 查询Lucene,拼装Ids
38             LuceneService luceneService = new LuceneServiceImpl();
39             List<SearchBean> lb = luceneService.search("posters", "id",
40                     "content", keyWords);
41             StringBuffer buffer = new StringBuffer();
42             for (int i = 0; i < lb.size(); i++) {
43                 buffer.append(lb.get(i).getId() + ",");
44             }
45             String searchIds = buffer.length() > 0 ? buffer.substring(0, buffer.length() - 1):"0";
46             entity.setPoster_title(searchIds);// 借用一下这个字段
47 
48             return postersMapper.search(sort, order, entity);// i, rows,
49         } else {
50             return postersMapper.listLimit(sort, order, entity);
51         }
52     }
53     
54     @Override
55     public List<Posters> postersForLucene(String sort, String order, Posters entity) {// int
56                                                                                 // i,
57                                                                                 // int
58                                                                                 // rows,
59         // TODO Auto-generated method stub
60         return postersMapper.postersForLucene(sort, order, entity);// i, rows,
61     }

使用的是lucene 5.3.1,不同的版本,方法有差异。

不足之处:数据修改后,不能更新Lucene。

 

另外要使用@Autowired时,不能自动初始化,使用以下方式就可以了。new Object是不行的。

PosterService posterService=(PosterService)SpringUtil.getBean("posterService");

代码垃圾,仅供参考备忘。

posted @ 2015-11-05 17:29  martin__zhu  阅读(264)  评论(0)    收藏  举报