实体类设计
@Document(indexName="blog")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
@Id
private String id;
@Field(type = FieldType.Text,analyzer = "ik_max_word", searchAnalyzer = "ik_max_word",store = true)
private String firstname;
@Field(type = FieldType.Text,analyzer = "ik_max_word", searchAnalyzer = "ik_max_word",store = true)
private String lastname;
private int age;
}
ik_smart ik_max_word 前面是粗粒度分词,后面是细粒度分词,也就是说后面分词个数比前面多
查询方式1
@Test
public void testOps(){
// 构建查询条件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本分词查询
String preTags = "<strong>";
String postTags = "</strong>";
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags(preTags);//设置前缀
highlightBuilder.postTags(postTags);//设置后缀
highlightBuilder.field("firstname");//设置高亮字段
String text = "丈二金刚摸不着头脑的";
queryBuilder.withQuery(QueryBuilders.matchQuery("firstname", text));
queryBuilder.withHighlightBuilder(highlightBuilder);
NativeSearchQuery query = queryBuilder.build();
SearchHits<Blog> search = elasticsearchOperations.search(query, Blog.class);
long totalHits = search.getTotalHits();
System.out.println("totalHits = " + totalHits);
Iterator<SearchHit<Blog>> iterator = search.stream().iterator();
while (iterator.hasNext()) {
SearchHit<Blog> next = iterator.next();
Blog content = next.getContent();
List<String> firstname = next.getHighlightField("firstname");
for (String s : firstname) {
System.out.println(s);
}
}
}
方式二
@Test
public void testH21231111() {
List<SearchHit<Blog>> searchHitList = blogRepository.findByFirstname("丈二金刚摸不着头脑的");
for (SearchHit<Blog> customerSearchHit : searchHitList) {
Blog content = customerSearchHit.getContent();
System.out.println(content);
List<String> firstname = customerSearchHit.getHighlightField("firstname");
for (String s : firstname) {
System.out.println(s);
}
}
}