springboot集成elasticsearch,通过实体类创建索引,实现搜索提示补全功能
注:在此之前需要下载elasticsearch以及拼音分词器。可以查看这篇文章,免费下载,下载完直接解压就行。https://download.csdn.net/download/weixin_47874230/86514890
一、引入pom依赖
spring-data-elasticsearch版本需要与springboot版本对应,此处使用springboot版本为2.2.13.RELEASE文章来源:https://www.toymoban.com/news/detail-697636.html
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.2.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
二、修改yml文件
server:
port: 8080
spring:
elasticsearch:
rest:
uris:
- http://localhost:9200
三、创建实体类GoodsDoc.java
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.*;
import org.springframework.data.elasticsearch.core.completion.Completion;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "goods", shards = 1, replicas = 0) //type = "_doc" ,
public class GoodsDoc {
@Id
@Field(type = FieldType.Keyword)
private String id;
@CompletionField(analyzer = "ik_smart", searchAnalyzer = "ik_smart", maxInputLength = 100)
private Completion title;
@Field(type = FieldType.Text) //测试用,当name和title值相同时,检索结果区别,title查出结果数据较少,name为正常查询
private String name;
@Field(type = FieldType.Float)
private float price;
@Field(type = FieldType.Text)
private String desc;
@Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdTime;
@Field(type = FieldType.Date, format = DateFormat.custom, pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date modifiedTime;
}
四、创建GoodsMapper.java
import com.example.elasticsearch7demo.entity.GoodsDoc;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface GoodsMapper extends ElasticsearchRepository<GoodsDoc, String> {
}
五、创建GoodsController.java
包含创建索引,添加数据,测试功能
import com.example.elasticsearch7demo.mapper.GoodsMapper;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.completion.Completion;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping
public class GoodsController {
@Autowired
private ElasticsearchRestTemplate restTemplate;
@Autowired
private GoodsMapper goodsMapper;
//创建索引和映射
@GetMapping("/create")
public void testCreateIndex(){
restTemplate.createIndex(GoodsDoc.class);
restTemplate.putMapping(GoodsDoc.class);
}
//添加数据
@GetMapping("/insert")
public void addData() throws Exception {
List<GoodsDoc> orderDocs = new ArrayList<>();
List<String> suggestList = new ArrayList<>();
String title = "笔记本电脑";
suggestList.add(title); //可以把多个内容作为suggest的数据源
Completion suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
GoodsDoc orderDoc = new GoodsDoc("1", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "笔记本";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("2", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "笔记本支架";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("3", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "笔记本内存条";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("4", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "联想笔记本";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("5", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "华硕笔记本";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("6", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "联想台式机";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("7", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "笔记本电脑是联想牌子的";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("8", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
suggestList = new ArrayList<>();
title = "你喜欢什么牌子的笔记本?";
suggestList.add(title);
suggest = new Completion(suggestList.toArray(new String[suggestList.size()]));
orderDoc = new GoodsDoc("9", suggest,title, 100,"笔记本电脑非常方便",new Date(),new Date());
orderDocs.add(orderDoc);
goodsMapper.saveAll(orderDocs);
}
//测试
@GetMapping("/test")
public List<String> search(@RequestParam("keywords") String keywords){
// 使用suggest进行标题联想
CompletionSuggestionBuilder suggest = SuggestBuilders.completionSuggestion("title")
//根据什么前缀来联想
// .prefix("笔记本")
.prefix(keywords)
// 跳过重复过滤
.skipDuplicates(true)
// 匹配数量
.size(10);
SuggestBuilder suggestBuilder = new SuggestBuilder();
suggestBuilder.addSuggestion("title-suggest",suggest);
//执行查询
SearchResponse suggestResp = restTemplate.suggest(suggestBuilder, GoodsDoc.class);
//拿到Suggest结果
Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> orderSuggest = suggestResp
.getSuggest().getSuggestion("title-suggest");
// 处理返回结果
List<String> suggests = orderSuggest.getEntries().stream()
.map(x -> x.getOptions().stream()
.map(y->y.getText().toString())
.collect(Collectors.toList())).findFirst().get();
// 输出内容
for (String str : suggests) {
System.out.println("自动补全 = " + str);
}
return suggests;
}
}
六、结果
文章来源地址https://www.toymoban.com/news/detail-697636.html
总结
以上就是记录的es实体类的创建以及搜索提示补全功能内容。
到了这里,关于springboot集成elasticsearch,实现搜索提示补全功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!