在SpringBoot容器启动时,会默认初始化标有 @Document 注解的类,若ES中未创建索引,则会以 @Document 中的 indexName 为索引名创建索引,若ES中已存在该索引,则会忽略。在这里先贴一下ES实体类
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Document(indexName = "student")
public class Student implements Serializable {
private static final long serialVersionUID = 3312542029426741325L;
@Id
private String id;
/**
* Keyword类型不可分词
*/
@Field(type = FieldType.Keyword)
private String name;
/**
* IK提供两种分词ik_smart和ik_max_word,其中ik_smart为最少切分,ik_max_word为最细粒度划分
* text类型可分词,手动设置分词器
*/
@Field(type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_max_word")
private String content;
@Field(type=FieldType.Auto)
private String address;
@CompletionField(analyzer="ik_smart",searchAnalyzer="ik_smart", maxInputLength = 100)
private Completion suggest;
}
项目启动后使用命令在kibana查看索引结构
GET /student/_mapping
结构如下:
{
"student" : {
"mappings" : {
"properties" : {
"_class" : {
"type" : "keyword",
"index" : false,
"doc_values" : false
},
"address" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"content" : {
"type" : "text",
"analyzer" : "ik_smart",
"search_analyzer" : "ik_max_word"
},
"name" : {
"type" : "keyword"
},
"suggest" : {
"type" : "completion",
"analyzer" : "ik_smart",
"preserve_separators" : true,
"preserve_position_increments" : true,
"max_input_length" : 100
}
}
}
}
}
新增数据:
@Resource
private ElasticsearchOperations elasticsearchOperations;
@RequestMapping("add")
public Student studentAdd(Student student){
//搜索补全使用
List<String> suggestList = new ArrayList<>();
suggestList.add(student.getAddress());
student.setSuggest(new Completion(suggestList.toArray(new String[suggestList.size()])));
return elasticsearchOperations.save(student);
}
之后可以使用命令查看数据
GET /student/_search
搜索提示代码:
@RequestMapping("suggest")
public List<String> suggest(String keyword){
// 使用suggest进行标题联想
CompletionSuggestionBuilder suggest = SuggestBuilders.completionSuggestion("suggest")
// 关键字(参数传此)
.prefix(keyword)
// 重复过滤
.skipDuplicates(true)
// 匹配数量
.size(10);
SuggestBuilder suggestBuilder = new SuggestBuilder();
suggestBuilder.addSuggestion("my-suggest",suggest);
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withSuggestBuilder(suggestBuilder).build();
// 查询
SearchHits<Student> search = elasticsearchOperations.search(searchQuery, Student.class);
Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestion = search.getSuggest().getSuggestion("my-suggest");
// 处理返回
List<String> suggests = suggestion.getEntries().stream().map(x -> x.getOptions().stream().map(y->y.getText().toString()).collect(Collectors.toList())).findFirst().get();
return suggests;
}
查看结果: