SearchUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package com.uas.search.util;
  2. import com.uas.search.LuceneProperties;
  3. import com.uas.search.constant.SearchConstants;
  4. import com.uas.search.constant.model.SPage;
  5. import com.uas.search.exception.SearchException;
  6. import com.uas.search.model.*;
  7. import com.uas.search.support.IndexSearcherManager;
  8. import org.apache.lucene.analysis.Analyzer;
  9. import org.apache.lucene.analysis.TokenStream;
  10. import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
  11. import org.apache.lucene.document.Document;
  12. import org.apache.lucene.index.Term;
  13. import org.apache.lucene.search.BooleanClause.Occur;
  14. import org.apache.lucene.search.*;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import org.springframework.util.CollectionUtils;
  18. import org.springframework.util.StringUtils;
  19. import org.wltea.analyzer.lucene.IKAnalyzer;
  20. import java.io.IOException;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. /**
  24. * 搜索相关的工具类
  25. *
  26. * @author sunyj
  27. * @since 2016年10月17日 下午1:56:16
  28. */
  29. public class SearchUtils {
  30. /**
  31. * 默认的页码
  32. */
  33. private static final int PAGE_INDEX = 1;
  34. /**
  35. * 默认每页的大小
  36. */
  37. private static final int PAGE_SIZE = 20;
  38. private static Logger logger = LoggerFactory.getLogger(SearchUtils.class);
  39. /**
  40. * IndexSearcher的管理器
  41. */
  42. private static IndexSearcherManager searcherManager = IndexSearcherManager.getInstance();
  43. private static LuceneProperties luceneProperties = ContextUtils.getBean(LuceneProperties.class);
  44. /**
  45. * 判断搜索词是否为无效的(比如只包含特殊字符,不含有任何字母、数字、汉字等有意义的字符)
  46. *
  47. * @param keyword
  48. * @return 搜索词是否无效
  49. */
  50. public static boolean isKeywordInvalid(String keyword) {
  51. if (!StringUtils.isEmpty(keyword)) {
  52. // 将特殊字符剔除
  53. keyword = keyword.replaceAll("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、? ]+", "");
  54. return StringUtils.isEmpty(keyword);
  55. }
  56. return true;
  57. }
  58. /**
  59. * 对搜索词进行分词后组合得到BooleanQuery
  60. *
  61. * @param field
  62. * 搜索的域名
  63. * @param keyword
  64. * 搜索关键词
  65. * @return
  66. */
  67. public static BooleanQuery getBooleanQuery(String field, String keyword) {
  68. return getBooleanQuery(field, keyword, true, Occur.MUST);
  69. }
  70. /**
  71. * 对搜索词进行分词后组合得到BooleanQuery
  72. *
  73. * @param field
  74. * 搜索的域名
  75. * @param keyword
  76. * 搜索关键词
  77. * @param useSmart
  78. * 是否以最大粒度进行分词
  79. * @param occur
  80. * 多个Query之间的关系
  81. * @return
  82. */
  83. public static BooleanQuery getBooleanQuery(String field, String keyword, boolean useSmart, Occur occur) {
  84. if (StringUtils.isEmpty(field) || StringUtils.isEmpty(keyword)) {
  85. return null;
  86. }
  87. BooleanQuery booleanQuery = new BooleanQuery();
  88. Analyzer analyzer = new IKAnalyzer(useSmart);
  89. try {
  90. TokenStream tokenStream = analyzer.tokenStream(field, keyword);
  91. tokenStream.reset();
  92. CharTermAttribute cta = tokenStream.addAttribute(CharTermAttribute.class);
  93. while (tokenStream.incrementToken()) {
  94. booleanQuery.add(new PrefixQuery(new Term(field, cta.toString())), occur);
  95. }
  96. tokenStream.close();
  97. analyzer.close();
  98. } catch (IOException e) {
  99. logger.error("", e);
  100. }
  101. return booleanQuery;
  102. }
  103. /**
  104. * 对搜索词进行分词后组合得到RegexpQuery
  105. *
  106. * @param field
  107. * 搜索的域名
  108. * @param keyword
  109. * 搜索关键词
  110. * @return
  111. */
  112. // 如果用正则表达式进行搜索,就不需要再分词(分词的字段可能会导致边界问题)
  113. public static RegexpQuery getRegexpQuery(String field, String keyword) {
  114. if (StringUtils.isEmpty(field)) {
  115. return null;
  116. }
  117. // TODO 针对的是分词了的字段(未分词的字段可能搜索不准确)
  118. return new RegexpQuery(new Term(field, ".*" + keyword.toLowerCase() + ".*"));
  119. }
  120. /**
  121. * 获取指定表的IndexSearcher对象,若为空,抛出异常
  122. *
  123. * @param tableName
  124. * 表名
  125. * @return IndexSearcher对象
  126. */
  127. public static IndexSearcher getIndexSearcher(String tableName) {
  128. IndexSearcher indexSearcher = searcherManager.get(tableName);
  129. if (indexSearcher == null) {
  130. throw new SearchException("获取索引文件失败");
  131. }
  132. return indexSearcher;
  133. }
  134. /**
  135. * 释放indexSearcher
  136. *
  137. * @param indexSearcher
  138. */
  139. public static void releaseIndexSearcher(IndexSearcher indexSearcher) {
  140. searcherManager.release(indexSearcher);
  141. }
  142. /**
  143. * 根据域和搜索词获取指定表的Document(每个id最多只能对应一条数据)
  144. *
  145. * @param tableName
  146. * 表名
  147. * @param field
  148. * 搜索域
  149. * @param id
  150. * 搜索词
  151. * @return Document
  152. */
  153. public static Document getDocumentById(String tableName, String field, Long id) {
  154. if (id == null) {
  155. throw new SearchException("输入无效:" + id);
  156. }
  157. return getDocumentById(tableName, field, Long.toString(id));
  158. }
  159. /**
  160. * 根据域和搜索词获取指定表的Document(每个id最多只能对应一条数据)
  161. *
  162. * @param tableName
  163. * 表名
  164. * @param field
  165. * 搜索域
  166. * @param id
  167. * 搜索词
  168. * @return Document
  169. */
  170. public static Document getDocumentById(String tableName, String field, String id) {
  171. if (StringUtils.isEmpty(field) || StringUtils.isEmpty(id)) {
  172. throw new SearchException("搜索的域和搜索词不能为空");
  173. }
  174. TermQuery termQuery = new TermQuery(new Term(field, id));
  175. List<Document> documents = getDocuments(tableName, termQuery).getContent();
  176. if (CollectionUtils.isEmpty(documents)) {
  177. return null;
  178. } else if (documents.size() > 1) {
  179. throw new SearchException("索引中存在不止一个对象:" + field + "=" + id);
  180. }
  181. return documents.get(0);
  182. }
  183. /**
  184. * 根据查询条件获取指定表的Document列表
  185. *
  186. * @param tableName
  187. * 表名
  188. * @param query
  189. * 查询条件
  190. * @return
  191. */
  192. public static SPage<Document> getDocuments(String tableName, Query query) {
  193. return getDocuments(tableName, query, null, null);
  194. }
  195. /**
  196. * 根据查询条件获取指定表的Document列表
  197. *
  198. * @param tableName
  199. * 表名
  200. * @param query
  201. * 查询条件
  202. * @param page
  203. * 页码
  204. * @param size
  205. * 页大小
  206. * @return
  207. */
  208. public static SPage<Document> getDocuments(String tableName, Query query, Integer page, Integer size) {
  209. if (query == null) {
  210. throw new SearchException("query不能为null");
  211. }
  212. SPage<Document> sPage = new SPage<>();
  213. if (page != null && page > 0) {
  214. sPage.setPage(page);
  215. } else {
  216. sPage.setPage(PAGE_INDEX);
  217. sPage.setFirst(true);
  218. }
  219. if (size != null && size > 0) {
  220. sPage.setSize(size);
  221. } else {
  222. sPage.setSize(PAGE_SIZE);
  223. }
  224. IndexSearcher indexSearcher = getIndexSearcher(tableName);
  225. TopDocs topDocs;
  226. try {
  227. // 如果页码不为1
  228. if (sPage.getPage() > 1) {
  229. TopDocs previousTopDocs = null;
  230. previousTopDocs = indexSearcher.search(query, (sPage.getPage() - 1) * sPage.getSize());
  231. int totalHits = previousTopDocs.totalHits;
  232. ScoreDoc[] previousScoreDocs = previousTopDocs.scoreDocs;
  233. if ((sPage.getPage() - 1) * sPage.getSize() >= totalHits) {
  234. throw new SearchException("页码过大:元素总数量为" + totalHits);
  235. }
  236. topDocs = indexSearcher.searchAfter(previousScoreDocs[previousScoreDocs.length - 1], query,
  237. sPage.getSize());
  238. } else {
  239. sPage.setFirst(true);
  240. topDocs = indexSearcher.search(query, sPage.getSize());
  241. }
  242. int totalHits = topDocs.totalHits;
  243. // 设置总元素个数、页数等信息
  244. sPage.setTotalElement(totalHits);
  245. int totalPage = (int) Math.ceil(totalHits / (1.0 * sPage.getSize()));
  246. sPage.setTotalPage(totalPage);
  247. if (totalPage == sPage.getPage()) {
  248. sPage.setLast(true);
  249. }
  250. List<Document> documents = new ArrayList<>();
  251. for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
  252. documents.add(indexSearcher.doc(scoreDoc.doc));
  253. }
  254. sPage.setContent(documents);
  255. } catch (IOException e) {
  256. throw new SearchException(e).setDetailedMessage(e);
  257. } finally {
  258. releaseIndexSearcher(indexSearcher);
  259. }
  260. return sPage;
  261. }
  262. /**
  263. * 获取各表索引的id字段名
  264. *
  265. * @param tableName
  266. * @return
  267. */
  268. public static String getIdField(String tableName) {
  269. if (tableName == null) {
  270. return null;
  271. }
  272. if (tableName.equals(SearchConstants.KIND_TABLE_NAME)) {
  273. return SearchConstants.KIND_ID_FIELD;
  274. } else if (tableName.equals(SearchConstants.BRAND_TABLE_NAME)) {
  275. return SearchConstants.BRAND_ID_FIELD;
  276. } else if (tableName.equals(SearchConstants.COMPONENT_TABLE_NAME)) {
  277. return SearchConstants.COMPONENT_ID_FIELD;
  278. } else if (tableName.equals(SearchConstants.GOODS_TABLE_NAME)) {
  279. return SearchConstants.GOODS_ID_FIELD;
  280. } else if (tableName.equals(SearchConstants.ORDER_TABLE_NAME)) {
  281. return SearchConstants.ORDER_ID_FIELD;
  282. } else if (tableName.equals(SearchConstants.ORDER_INVOICE_TABLE_NAME)) {
  283. return SearchConstants.ORDER_INVOICE_ID_FIELD;
  284. } else if (tableName.equals(SearchConstants.PURCHASE_TABLE_NAME)) {
  285. return SearchConstants.PURCHASE_ID_FIELD;
  286. } else if (tableName.equals(SearchConstants.PURCHASE_INVOICE_TABLE_NAME)) {
  287. return SearchConstants.PURCHASE_INVOICE_ID_FIELD;
  288. }
  289. throw new SearchException("不支持的表:" + tableName);
  290. }
  291. /**
  292. * 获取所有需要建立索引的表名
  293. *
  294. * @return
  295. */
  296. public static List<String> getTableNames() {
  297. List<String> tableNames = new ArrayList<>();
  298. tableNames.add(SearchConstants.KIND_TABLE_NAME);
  299. tableNames.add(SearchConstants.BRAND_TABLE_NAME);
  300. tableNames.add(SearchConstants.COMPONENT_TABLE_NAME);
  301. tableNames.add(SearchConstants.GOODS_TABLE_NAME);
  302. tableNames.add(SearchConstants.ORDER_TABLE_NAME);
  303. tableNames.add(SearchConstants.ORDER_INVOICE_TABLE_NAME);
  304. tableNames.add(SearchConstants.PURCHASE_TABLE_NAME);
  305. tableNames.add(SearchConstants.PURCHASE_INVOICE_TABLE_NAME);
  306. return tableNames;
  307. }
  308. /**
  309. * 获取指定的实体类对应的需要建立索引的表名
  310. *
  311. * @param clazz
  312. * @return
  313. */
  314. public static String getTableName(Class<?> clazz) {
  315. if (clazz == null) {
  316. return null;
  317. }
  318. if (clazz == Kind.class) {
  319. return SearchConstants.KIND_TABLE_NAME;
  320. } else if (clazz == Brand.class) {
  321. return SearchConstants.BRAND_TABLE_NAME;
  322. } else if (clazz == Component.class) {
  323. return SearchConstants.COMPONENT_TABLE_NAME;
  324. } else if (clazz == Goods.class) {
  325. return SearchConstants.GOODS_TABLE_NAME;
  326. } else if (clazz == Order.class) {
  327. return SearchConstants.ORDER_TABLE_NAME;
  328. } else if (clazz == OrderInvoice.class) {
  329. return SearchConstants.ORDER_INVOICE_TABLE_NAME;
  330. } else if (clazz == Purchase.class) {
  331. return SearchConstants.PURCHASE_TABLE_NAME;
  332. } else if (clazz == PurchaseInvoice.class) {
  333. return SearchConstants.PURCHASE_INVOICE_TABLE_NAME;
  334. } else {
  335. throw new SearchException("该实体类没有对应的需要建立索引的表:" + clazz);
  336. }
  337. }
  338. /**
  339. * 获取指定表的索引路径
  340. *
  341. * @param tableName
  342. * 指定表
  343. * @return 索引路径
  344. */
  345. public static String getIndexPath(String tableName) {
  346. if (tableName == null) {
  347. return null;
  348. }
  349. return luceneProperties.getIndexesDir() + "/" + tableName;
  350. }
  351. /**
  352. * 获取指定表的数据路径
  353. *
  354. * @param tableName
  355. * 指定表
  356. * @return 数据路径
  357. */
  358. public static String getDataPath(String tableName) {
  359. if (tableName == null) {
  360. return null;
  361. }
  362. return luceneProperties.getDataDir() + "/" + tableName;
  363. }
  364. }