SearchUtils.java 12 KB

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