SearchUtils.java 14 KB

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