lucene Spring

来源:互联网 发布:d3.v3.min.js引用 编辑:程序博客网 时间:2024/05/01 19:26

spring框架下配置lucene

mvc-config.xml:

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:util="http://www.springframework.org/schema/util"  
  7.     xsi:schemaLocation="  
  8.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  10.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  11.         http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util-3.0.xsd"  
  12.         default-autowire="byName" >  
  13.           
  14.           
  15.     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  16.         <property name="messageConverters">  
  17.             <list>  
  18.                 <bean class = "org.springframework.http.converter.StringHttpMessageConverter">   
  19.                     <property name = "supportedMediaTypes">   
  20.                         <list><value>text/plain;charset=UTF-8</value></list>  
  21.                     </property>  
  22.                 </bean>  
  23.             </list>  
  24.         </property>  
  25.     </bean>  
  26.     <context:component-scan base-package="com.jizhong" />  
  27.     <mvc:annotation-driven/>  
  28.       
  29.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  30.         <property name="prefix" value="/" />  
  31.         <property name="suffix" value=".jsp" />  
  32.     </bean>  
  33.       
  34.       
  35.     <!-- LUCENE SEARCH CONFIG -->  
  36.     <!-- 设置字段内容长度,这里不做限定   -->  
  37.     <bean id="MAXFIELDLENGTH2" class="org.apache.lucene.index.IndexWriter.MaxFieldLength.UNLIMITED" />  
  38.     <!-- set your analyzer, to be used by the IndexWriter and QueryParser ,关于分词器,因为我们主要进行中文搜索,所以要选择好点的中文分词器,我选择了paoding-->  
  39.     <bean id="luceneAnalyzer" class="net.paoding.analysis.analyzer.PaodingAnalyzer">  
  40.     </bean>   
  41.       
  42.     <!-- set your Lucene directory -->  
  43.     <!-- in this case I am pulling the location from a properties file -->  
  44.     <!-- also, using the SimpleFSLockFactory ,数据文件存放位置设置-->  
  45.     <bean id="luceneDirectory" class="org.apache.lucene.store.SimpleFSDirectory" >     
  46.         <constructor-arg>       
  47.             <bean class="java.io.File">         
  48.                 <constructor-arg value="D:\\common\\hahaha" />       
  49.             </bean>     
  50.         </constructor-arg>     
  51.     </bean>   
  52.       
  53.     <!-- now you're ready to define the IndexWriter,这里创建 IndexWriter并引入相关bean-->  
  54.     <bean id="indexWriter" class="org.apache.lucene.index.IndexWriter">     
  55.         <constructor-arg ref="luceneDirectory" />  
  56.         <constructor-arg ref="luceneAnalyzer" />  
  57.         <constructor-arg name="create" value="false" />  
  58.         <constructor-arg ref="MAXFIELDLENGTH2" />  
  59.     </bean>    
  60.       
  61.     <!-- define the IndexSearcher ,这里创建IndexSearcher-->  
  62.    <bean id="indexSearcher" class="org.apache.lucene.search.IndexSearcher">  
  63.       <constructor-arg ref="luceneDirectory" />  
  64.    </bean>   
  65.    
  66.      
  67. </beans>  

 

以上是spring配置文件中关于lucene的代码片段,看起来是不是很简单?





我们继续看代码


Java代码  收藏代码
  1. package com.jizhong.mmmmm.controller;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.StringReader;   
  5.   
  6. import javax.servlet.http.HttpServletRequest;   
  7.   
  8. import org.apache.log4j.Logger;   
  9. import org.apache.lucene.analysis.Analyzer;   
  10. import org.apache.lucene.analysis.TokenStream;   
  11. import org.apache.lucene.analysis.tokenattributes.TermAttribute;   
  12. import org.apache.lucene.document.Document;   
  13. import org.apache.lucene.document.Field;   
  14. import org.apache.lucene.document.Field.Index;   
  15. import org.apache.lucene.document.Field.Store;   
  16. import org.apache.lucene.document.NumericField;   
  17. import org.apache.lucene.index.CorruptIndexException;   
  18. import org.apache.lucene.index.IndexReader;   
  19. import org.apache.lucene.index.IndexWriter;   
  20. import org.apache.lucene.index.Term;   
  21. import org.apache.lucene.queryParser.MultiFieldQueryParser;   
  22. import org.apache.lucene.queryParser.ParseException;   
  23. import org.apache.lucene.queryParser.QueryParser;   
  24. import org.apache.lucene.search.BooleanClause;   
  25. import org.apache.lucene.search.BooleanQuery;   
  26. import org.apache.lucene.search.IndexSearcher;   
  27. import org.apache.lucene.search.Query;   
  28. import org.apache.lucene.search.ScoreDoc;   
  29. import org.apache.lucene.search.Sort;   
  30. import org.apache.lucene.search.SortField;   
  31. import org.apache.lucene.search.TopDocs;   
  32. import org.apache.lucene.util.Version;   
  33. import org.springframework.beans.factory.annotation.Autowired;   
  34. import org.springframework.stereotype.Controller;   
  35. import org.springframework.ui.ModelMap;   
  36. import org.springframework.web.bind.annotation.RequestMapping;   
  37. import org.springframework.web.bind.annotation.RequestMethod;   
  38.   
  39. @Controller   
  40. public class LuceneController {   
  41.   
  42. private static Logger logger = Logger.getLogger(LuceneController.class);   
  43.   
  44. @Autowired(required = false)//这里我写了required = false,需要时再引入,不写的话会报错,大家有更好解决方案请留言哈   
  45. private Analyzer myAnalyzer;   
  46. @Autowired(required = false)   
  47. private IndexWriter indexWriter;   
  48. @Autowired(required = false)   
  49. private IndexSearcher searcher;   
  50.   
  51. @RequestMapping(value = "search.do", method = RequestMethod.GET)   
  52. public String testsSearch(HttpServletRequest request, ModelMap modelMap) throws Exception {   
  53. search();   
  54. return "test";   
  55. }   
  56.   
  57. @RequestMapping(value = "idSearch.do", method = RequestMethod.GET)   
  58. public String idSearch(HttpServletRequest request, ModelMap modelMap) throws Exception {   
  59. idSearch();   
  60. return "test";   
  61. }   
  62.   
  63. @RequestMapping(value = "moreSearch.do", method = RequestMethod.GET)   
  64. public String moreSearch(HttpServletRequest request, ModelMap modelMap) throws Exception {   
  65. searchMore();   
  66. return "test";   
  67. }   
  68.   
  69. @RequestMapping(value = "create.do", method = RequestMethod.GET)   
  70. public String testsCreate(HttpServletRequest request, ModelMap modelMap) throws Exception {   
  71. create("整形值添加");   
  72. // create(request.getParameter("name"));   
  73. return "test";   
  74. }   
  75.   
  76. @RequestMapping(value = "delete.do", method = RequestMethod.GET)   
  77. public String delete(HttpServletRequest request, ModelMap modelMap) throws Exception {   
  78. delete("id", request.getParameter("id"));   
  79. return "test";   
  80. }   
  81.   
  82. @RequestMapping(value = "optimize.do", method = RequestMethod.GET)   
  83. public String optimize(HttpServletRequest request, ModelMap modelMap) throws Exception {   
  84. indexWriter.optimize();//优化索引方法,不建议经常调用,会很耗时,隔段时间调优下即可   
  85. return "test";   
  86. }   
  87. //关于更新一个文档要注意一点,虽然它提供了updateDocument,但我觉得他是先删再加,所以大家要把所以值都写上,虽然可能只更新一个字段   
  88. @RequestMapping(value = "update.do", method = RequestMethod.GET)   
  89. public String update(HttpServletRequest request, ModelMap modelMap) throws Exception {   
  90. Term term = new Term("id""1999991");   
  91. Document doc = new Document();   
  92. doc.add(new Field("id", String.valueOf(1999991), Store.YES, Index.NOT_ANALYZED));   
  93. doc.add(new Field("name"555555 + "555555" + 555555, Store.YES, Index.ANALYZED));   
  94. doc.add(new Field("level1", String.valueOf(555555), Store.YES, Index.NOT_ANALYZED));   
  95. doc.add(new Field("level2", String.valueOf(555555), Store.YES, Index.NOT_ANALYZED));   
  96. doc.add(new Field("level3", String.valueOf(555555), Store.YES, Index.NOT_ANALYZED));   
  97. doc.add(new Field("brand_id", String.valueOf(555555 + 100000), Store.YES, Index.NOT_ANALYZED));   
  98. indexWriter.updateDocument(term, doc);   
  99. indexWriter.commit();//凡是涉及到索引变化的动作都要提交才能生效   
  100. return "test";   
  101. }   
  102. //delete,没啥说的哈   
  103. private void delete(String field, String text) throws CorruptIndexException, IOException {   
  104. Term term1 = new Term(field, text);   
  105. indexWriter.deleteDocuments(term1);   
  106. indexWriter.commit();   
  107. }   
  108.   
  109. public void create(String string) throws Exception {   
  110. long begin = System.currentTimeMillis();   
  111. for (int m = 604; m < 605; m++) {   
  112. for (int i = m * 10000; i < (m + 1) * 10000; i++) {   
  113. Document doc = new Document();   
  114. // doc.add(new Field("id", String.valueOf(i), Store.YES, Index.NOT_ANALYZED_NO_NORMS));   
  115. NumericField field = new NumericField("id"6, Field.Store.YES, false);   
  116. field.setIntValue(i);   
  117. doc.add(field);//这里不建议这样写,无论什么格式都以字符串形式灌入数据最好,否则会因为不匹配而查不到,经验之谈哈,如下面这样:   
  118. doc.add(new Field("name", i + string + i, Store.YES, Index.ANALYZED));//关于索引策略,建议需要模糊查询字段进行分词策略,其他则不分词   
  119. doc.add(new Field("level1", String.valueOf(3), Store.YES, Index.NOT_ANALYZED_NO_NORMS));   
  120. doc.add(new Field("level2", String.valueOf(2), Store.YES, Index.NOT_ANALYZED_NO_NORMS));   
  121. doc.add(new Field("level3", String.valueOf(1), Store.YES, Index.NOT_ANALYZED_NO_NORMS));   
  122. doc.add(new Field("brand_id", String.valueOf(i + 100000), Store.YES, Index.NOT_ANALYZED_NO_NORMS));   
  123. doc.add(new Field("hehe", String.valueOf(i + 100000), Store.YES, Index.NOT_ANALYZED_NO_NORMS));   
  124. indexWriter.addDocument(doc);   
  125. }   
  126. System.out.println(m);   
  127. }   
  128. indexWriter.commit();   
  129. System.out.println("create cost:" + (System.currentTimeMillis() - begin) / 1000 + "s");   
  130. }   
  131.   
  132. //这里的查询是说:搜索name字段关键词为“整形的”,level3字段值为1的内容,两者条件是 'and'的关系   
  133. public void search() throws Exception {   
  134. long begin = System.currentTimeMillis();   
  135. String[] queryString = { "整形""1" };//注意字段与值要一一对应哦,同下   
  136. String[] fields = { "name""level3" };////注意字段与值要一一对应哦,同上   
  137. BooleanClause.Occur[] clauses = { BooleanClause.Occur.MUST, BooleanClause.Occur.MUST };//这里就是 and 的关系,详细策略看文档哈   
  138. Query query = MultiFieldQueryParser.parse(Version.LUCENE_30, queryString, fields, clauses, myAnalyzer);   
  139. IndexReader readerNow = searcher.getIndexReader();   
  140. //这个判断很重要,就是当我们刚灌入了数据就希望查询出来,因为前者写索引时关闭了reader,所以我们现在查询时要打开它   
  141. if (!readerNow.isCurrent()) {   
  142. searcher = new IndexSearcher(readerNow.reopen());   
  143. }   
  144. System.out.println(searcher.maxDoc());   
  145. Sort sort = new Sort();   
  146. sort.setSort(new SortField("id", SortField.INT, true));   
  147. TopDocs topDocs = searcher.search(query, null53, sort);//排序策略   
  148. // TopDocs topDocs = searcher.search(query, 50);   
  149. for (ScoreDoc scoreDoc : topDocs.scoreDocs) {   
  150. Document doc = searcher.doc(scoreDoc.doc);   
  151. System.out.println("id:" + doc.get("id"));   
  152. System.out.println("name:" + doc.get("name"));   
  153. System.out.println("level3:" + doc.get("level3"));   
  154. System.out.println("new field:" + doc.get("hehe"));   
  155. }   
  156. System.out.println("search cost:" + (System.currentTimeMillis() - begin) / 1000 + "s");   
  157. }   
  158.   
  159. private void idSearch() throws ParseException, CorruptIndexException, IOException {   
  160. long begin = System.currentTimeMillis();   
  161. QueryParser qp = new QueryParser(Version.LUCENE_30, "id", myAnalyzer);   
  162.   
  163. Query query = qp.parse("4040011");   
  164. IndexReader readerNow = searcher.getIndexReader();   
  165. if (!readerNow.isCurrent()) {   
  166. searcher = new IndexSearcher(readerNow.reopen());   
  167. }   
  168. TopDocs topDocs = searcher.search(query, null53);   
  169. for (ScoreDoc scoreDoc : topDocs.scoreDocs) {   
  170. Document doc = searcher.doc(scoreDoc.doc);   
  171. System.out.println("id:" + doc.get("id"));   
  172. System.out.println("name:" + doc.get("name"));   
  173. System.out.println("level3:" + doc.get("level3"));   
  174. System.out.println("new field:" + doc.get("hehe"));   
  175. }   
  176. System.out.println("search cost:" + (System.currentTimeMillis() - begin) / 1000 + "s");   
  177. }   
  178.   
  179. public void searchMore() throws Exception {   
  180. long begin = System.currentTimeMillis();   
  181. String[] queryStringOne = { "kkk""222222" };   
  182. String[] queryStringTwo = { "99980""222222" };   
  183. String[] fields = { "name""level2" };   
  184. BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };   
  185. Query queryOne = MultiFieldQueryParser.parse(Version.LUCENE_30, queryStringOne, fields, clauses, myAnalyzer);   
  186. Query queryTwo = MultiFieldQueryParser.parse(Version.LUCENE_30, queryStringTwo, fields, clauses, myAnalyzer);   
  187. BooleanQuery booleanQuery = new BooleanQuery();   
  188. booleanQuery.add(queryOne, BooleanClause.Occur.MUST);   
  189. booleanQuery.add(queryTwo, BooleanClause.Occur.MUST);   
  190. IndexReader readerNow = searcher.getIndexReader();   
  191. if (!readerNow.isCurrent()) {   
  192. searcher = new IndexSearcher(readerNow.reopen());   
  193. }   
  194. System.out.println(searcher.maxDoc());   
  195. Sort sort = new Sort();   
  196. sort.setSort(new SortField("id", SortField.INT, true));   
  197. TopDocs topDocs = searcher.search(booleanQuery, null53, sort);   
  198. // TopDocs topDocs = searcher.search(query, 50);   
  199. for (ScoreDoc scoreDoc : topDocs.scoreDocs) {   
  200. Document doc = searcher.doc(scoreDoc.doc);   
  201. System.out.println("id:" + doc.get("id"));   
  202. System.out.println("name:" + doc.get("name"));   
  203. System.out.println("level3:" + doc.get("level3"));   
  204. System.out.println("new field:" + doc.get("hehe"));   
  205. }   
  206. System.out.println("search cost:" + (System.currentTimeMillis() - begin) / 1000 + "s");   
  207. }   
  208.   
  209. @RequestMapping(value = "result.do", method = RequestMethod.GET)   
  210. public void getAnalyzerResult() throws IOException {   
  211. StringReader reader = new StringReader("爱国者mp3");   
  212. TokenStream ts = myAnalyzer.tokenStream("name", reader);   
  213. ts.addAttribute(TermAttribute.class);   
  214. while (ts.incrementToken()) {   
  215. TermAttribute ta = ts.getAttribute(TermAttribute.class);   
  216. System.out.println(ta.term());   
  217. }   
  218. }   
  219.   
  220. }   

0 0
原创粉丝点击