前言
前端传递文本,后端对文本处理后进行模糊检索
一、使用到的组件
1.HanLP-分词
二、使用步骤
1.前端传递文本
例如传递内容如下
{multiQuery: 我需要自定义检索信息}
2.后端处理
String getMultiQuery = testInfo.getMultiQuery();
List<String> termsB = new ArrayList<>();
List<Term> termsA = HanLP.segment(getMultiQuery);
List<Term> termsA = HanLP.segment(getMultiQuery);
termsB = termsA.stream() .map(term -> term.word).collect(Collectors.toList());
如果需要限定分词可参照:
CustomDictionary.add(searchHit,"5000");
继续
String sql = "("+buildSearchQuery(termsB)+")";
like构建的函数
private String buildSearchQuery(List<String> terms) {
*
StringJoiner likeConditions = new StringJoiner(" OR ");
for (String term : terms) {
likeConditions.add("name LIKE '%" + term + "%'")
.add("code LIKE '%" + term + "%'");
}
return likeConditions.toString();
}
在mapper中:
<if test="multiQuery != null and multiQuery != ''" > and
<foreach collection="terms" item="term" separator=" OR ">
(name LIKE CONCAT('%', #{term}, '%')
OR code LIKE CONCAT('%', #{term}, '%')
</foreach>
</if>
这样就可以得到需求的数组。
3.高亮处理
是通过添加,<span> 标签将匹配到的文本包裹,以实现高亮
<span style='color:red;'>" + term + "</span>"
1.设置变化文本
private String highlightText(String text, String term) {
if (StringUtils.isEmpty(text)){
return text;
}
return text.replaceAll("(?i)" + term, "<span style='color:red;'>" + term + "</span>");
}
2.接口
OaReportInformation a = (OaReportInformation)highlightResult(result, finalTermsB,length);
3.方法
private Object highlightResult(Object result, List<String> terms, AtomicReference<Integer> length) {
for (String term : terms) {
Field[] fields = result.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
try {
Object value = field.get(result);
if (value != null && value instanceof String) {
String highlightedValue = highlightText((String) value, term);
length.set(length.get() + this.calculateHighlightedLength(highlightedValue));
field.set(result, highlightedValue);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
return result;
}
总结
实现文本高亮