1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
|
@RestController @Slf4j public class AppController {
@Value(value = "${analyzer.path}") private String path;
@RequestMapping(value = "add") public Object add() { ArticleVo articleEntity = new ArticleVo(); String test = RandomUtil.randomString(10); articleEntity.setId(test); articleEntity.setTitle(test); articleEntity.setContent(test); addOrUpIndex(articleEntity); Map<String, Object> data = new HashMap<>(); data.put("code", "200"); data.put("data", articleEntity); return data; }
@RequestMapping(value = "list/{keyWord}") public Object list(@PathVariable(required = false) String keyWord) { if (StrUtil.isEmpty(keyWord)) { keyWord = Strings.EMPTY; } List<ArticleVo> articleEntityList = fullTextSearch(keyWord, 1, 10); Map<String, Object> data = new HashMap<>(); data.put("code", "200"); data.put("data", articleEntityList); return data; }
@RequestMapping(value = "search") public Object search() { List<ArticleVo> articleEntityList = fullTextSearch(null, 1, 10); Map<String, Object> data = new HashMap<>(); data.put("code", "200"); data.put("data", articleEntityList); return data; }
@RequestMapping(value = "del/{id}") public Object del(@PathVariable(required = false) String id) { if (!StrUtil.isEmpty(id)) { deleteIndex(id); } Map<String, Object> data = new HashMap<>(); data.put("code", "200"); data.put("data", id); return data; }
private void addOrUpIndex(ArticleVo entity) { IndexWriter indexWriter = null; IndexReader indexReader = null; Directory directory = null; Analyzer analyzer = null; try { File indexFile = new File(path); File[] files = indexFile.listFiles(); analyzer = new IKAnalyzer(); directory = FSDirectory.open(Paths.get(path)); IndexWriterConfig writerConfig = new IndexWriterConfig(analyzer); indexWriter = new IndexWriter(directory, writerConfig); Document doc = new Document(); TopDocs topDocs = null; if (files != null && files.length != 0) { QueryParser queryParser = new QueryParser("id", analyzer); Query query = queryParser.parse(String.valueOf(entity.getId())); indexReader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader); topDocs = indexSearcher.search(query, 1); } doc.add(new StringField("id", String.valueOf(entity.getId()), Field.Store.YES)); doc.add(new TextField("title", entity.getTitle(), Field.Store.YES)); doc.add(new TextField("content", entity.getContent(), Field.Store.YES)); if (topDocs != null && topDocs.totalHits.value == 0) { indexWriter.addDocument(doc); } else { indexWriter.updateDocument(new Term("id", String.valueOf(entity.getId())), doc); } } catch (Exception e) { log.error("添加索引库出错 {}", e.getMessage()); throw new RuntimeException("添加索引库出错:" + e.getMessage()); } finally { if (indexWriter != null) { try { indexWriter.close(); } catch (IOException e) { log.error("indexWriter.close {}", e.getMessage()); } } if (indexReader != null) { try { indexReader.close(); } catch (IOException e) { log.error("indexReader.close {}", e.getMessage()); } } if (directory != null) { try { directory.close(); } catch (IOException e) { log.error("directory.close {}", e.getMessage()); } } if (analyzer != null) { analyzer.close(); } } }
public List<ArticleVo> fullTextSearch(String keyWord, Integer page, Integer limit) { List<ArticleVo> searchList = new ArrayList<>(10); File indexFile = new File(path); File[] files = indexFile.listFiles(); if (files == null || files.length == 0) { return searchList; } IndexReader indexReader = null; Directory directory = null; try (Analyzer analyzer = new IKAnalyzer()) { directory = FSDirectory.open(Paths.get(path)); QueryParser queryParser = new MultiFieldQueryParser(new String[]{"title", "content"}, analyzer); Query query = queryParser.parse(!StrUtil.isEmpty(keyWord) ? keyWord : "*:*"); indexReader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader); TopDocs topDocs = indexSearcher.search(query, 1); int start = (page - 1) * limit; int total = (int) topDocs.totalHits.value; ScoreDoc lastSd = null; if (page > 1) { int num = limit * (page - 1); TopDocs tds = indexSearcher.search(query, start); lastSd = tds.scoreDocs[num - 1]; } log.info("total {}", total); TopDocs tds = indexSearcher.searchAfter(lastSd, query, limit); QueryScorer queryScorer = new QueryScorer(query); Highlighter highlighter = null; if (StrUtil.isNotEmpty(keyWord)) { SimpleSpanFragmenter simpleSpanFragmenter = new SimpleSpanFragmenter(queryScorer, 200); SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<b><font color='red'>", "</font></b>"); highlighter = new Highlighter(formatter, queryScorer); highlighter.setTextFragmenter(simpleSpanFragmenter); } for (ScoreDoc sd : tds.scoreDocs) { Document doc = indexSearcher.doc(sd.doc); float score = sd.score; ArticleVo articleEntity = new ArticleVo(); String id = doc.get("id"); articleEntity.setId(id); articleEntity.setScore(score); if (StrUtil.isNotEmpty(keyWord)) { String titleBestFragment = highlighter.getBestFragment(analyzer, "title", doc.get("title")); String contentBestFragment = highlighter.getBestFragment(analyzer, "content", doc.get("content")); articleEntity.setTitle(titleBestFragment); articleEntity.setContent(contentBestFragment); } else { articleEntity.setTitle(doc.get("title")); articleEntity.setContent(doc.get("content")); } searchList.add(articleEntity); } return searchList; } catch (Exception e) { throw new RuntimeException("全文檢索出错:" + e.getMessage()); } finally { if (indexReader != null) { try { indexReader.close(); } catch (IOException e) { log.error("indexReader.close {}", e.getMessage()); } } if (directory != null) { try { directory.close(); } catch (IOException e) { log.error("directory.close {}", e.getMessage()); } } } }
private void deleteIndex(String id) { IndexWriter indexWriter = null; Directory directory = null; try (Analyzer analyzer = new IKAnalyzer()) { directory = FSDirectory.open(Paths.get(path)); IndexWriterConfig writerConfig = new IndexWriterConfig(analyzer); indexWriter = new IndexWriter(directory, writerConfig); indexWriter.deleteDocuments(new Term("id", id)); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("删除索引库出错:" + e.getMessage()); } finally { if (indexWriter != null) { try { indexWriter.close(); } catch (IOException e) { log.error("indexWriter.close {}", e.getMessage()); } } if (directory != null) { try { directory.close(); } catch (IOException e) { log.error("directory.close {}", e.getMessage()); } } } } }
|