es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程详解
作者:麦麦麦麦兜 时间:2023-12-06 07:34:14
注意:适用于springboot或者springcloud框架
1.首先下载相关文件
2.然后需要去启动相关的启动文件
3、导入相关jar包(如果有相关的依赖包不需要导入)以及配置配置文件,并且写一个dao接口继承一个类,在启动类上标注地址
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
## ElasticSearch - start
#开启 Elasticsearch 仓库(默认值:true)
spring.data.elasticsearch.repositories.enabled=true
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.cluster-name=myes
Shop:是下面创建的实体类名称(不能写错),String(传参时的类型,我这里id也给的String,因为integer报错)
import com.jk.user.model.Shop;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface EsDao extends ElasticsearchRepository<Shop,String> {
}
启动类上加上注解,后面跟的是dao的包名
@EnableElasticsearchRepositories(basePackages = "com.jk.web.dao")
4.实体类
indexName相当于数据库名, type 相当于表名 ,必须加上id,type 类型,analyzer 分词器名称(ik分词)
@Document(indexName = "zth",type = "t_shangpin")
public class Shop implements Serializable {
private static final long serialVersionUID = 2006762641515872124L;
private String id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
//商品名称
private String shopname;
//优惠价格
private Long reducedprice;
}
5.然后写controller层(这里直接注入dao接口),这里新增我选的是对象循环赋值,其实可以直接赋集合(参考)
//elasticsearch 生成表
// @RequestMapping("el")
// @ResponseBody
// public void el(){
// List<ElasticsearchBean> list=shoppService.queryelasticsearch();
// for (ElasticsearchBean ss: list) {
// ss.setScrenicName(ss.getScrenicName()+""+ss.getHotelName());
// }
// elasticsearch.saveAll(list);
// }
@Autowired
private EsDao esDao;
// 查询时需要
@Autowired
private ElasticsearchTemplate elasticsearchTemplate ;
//更新es服务器数据
@RequestMapping("addEs")
public boolean addShopEs() {
List<TShangpin> list = webUserService.queryShouye();//先去后台查出数据在赋值
Shop shop = new Shop();
try {
for (int i = 0; i < list.size(); i++) {
shop.setId(list.get(i).getShopid().toString());
shop.setShopname(list.get(i).getShopname());
esDao.save(shop);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//es搜索商品
@RequestMapping("queryShop")
public List ellist(String name, HttpSession session, Integer page, Integer rows){
if (name==null||"".equals(name)){
name = session.getAttribute("name").toString();
}
page=1;
rows=3;
HashMap<String, Object> resultMap = new HashMap<>();
//创建一个要搜索的索引库
SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient().prepareSearch("zth").setTypes("t_shangpin");
//创建组合查询
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
if (name!=null && !"".equals(name)){
boolQueryBuilder.should(QueryBuilders.matchQuery("shopname",name));
}
//设置查询的类型
searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequestBuilder.setQuery(boolQueryBuilder);
//分页
searchRequestBuilder.setFrom((page-1)*rows);
searchRequestBuilder.setSize(rows);
//设置高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("shopname")
.preTags("<font color='red'>")
.postTags("</font>");
searchRequestBuilder.highlighter(highlightBuilder);
//直接搜索返回响应数据 (json)
SearchResponse searchResponse = searchRequestBuilder.get();
SearchHits hits = searchResponse.getHits();
//获取总条数
long totalHits = hits.getTotalHits();
resultMap.put("total",totalHits);
ArrayList<Map<String,Object>> list = new ArrayList<>();
//获取Hits中json对象数据
SearchHit[] hits1 = hits.getHits();
for (int i=0;i<hits1.length;i++){
//获取Map对象
Map<String, Object> sourceAsMap = hits1[i].getSourceAsMap();
//获取高亮字段
Map<String, HighlightField> highlightFields = hits1[i].getHighlightFields();
//!!如果有高亮字段就取出赋给上面sourceAsMap中原有的名字给他替换掉!!
if (name!=null && !"".equals(name)){
sourceAsMap.put("shopname",highlightFields.get("shopname").getFragments()[0].toString());
}
list.add(sourceAsMap);
}
return list;
}
6.最后 如果无法搜索,可能是需要加一个ik的json文件,因为在实体类中规定了是ik分词器,如果不规定当它存进去后其实是还没有分词。
film-mapping.json
{
"film":
{
"_all":
{
"enabled": true
},
"properties":
{ "id":
{
"type": "integer"
},"name":
{
"type": "text", "analyzer": "ikSearchAnalyzer", "search_analyzer": "ikSearchAnalyzer", "fields":
{ "pinyin": {
"type": "text", "analyzer": "pinyinSimpleIndexAnalyzer", "search_analyzer": "pinyinSimpleIndexAnalyzer"
} } },
"nameOri": { "type": "text"
},"publishDate":
{ "type": "text" },"type":
{ "type": "text"
},"language":
{ "type": "text"
},"fileDuration":
{ "type": "text"
},"director":
{ "type": "text",
"index": "true", "analyzer": "ikSearchAnalyzer"
},"created":
{
"type": "date", "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
} } } }
film-setting.json
{ "index": { "analysis":
{ "filter":
{ "edge_ngram_filter":
{ "type": "edge_ngram", "min_gram": 1, "max_gram": 50
},"pinyin_simple_filter":
{
"type": "pinyin", "first_letter": "prefix", "padding_char": " ", "limit_first_letter_length": 50, "lowercase": true
}
},"char_filter":
{
"tsconvert": { "type": "stconvert", "convert_type": "t2s"
}
},"analyzer":
{ "ikSearchAnalyzer":
{ "type": "custom", "tokenizer": "ik_max_word", "char_filter": [ "tsconvert" ]
},"pinyinSimpleIndexAnalyzer":
{ "tokenizer": "keyword", "filter": [ "pinyin_simple_filter", "edge_ngram_filter", "lowercase" ]
} } } } }
来源:https://blog.csdn.net/weixin_44824381/article/details/106896325
标签:elasticsearch,整合,SpringCloud
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
C#计算矩阵的逆矩阵方法实例分析
2021-11-06 18:24:29
![](https://img.aspxhome.com/file/2023/7/69197_0s.png)
DevExpress TreeList 常见问题解决方法
2022-07-15 18:16:54
基于Java语言实现Socket通信的实例
2021-08-06 17:17:50
![](https://img.aspxhome.com/file/2023/5/68705_0s.jpg)
java按字节截取带有汉字的字符串的解法(推荐)
2022-10-08 23:49:49
SpringBoot封装JDBC的实现步骤
2022-09-13 04:04:31
![](https://img.aspxhome.com/file/2023/0/70340_0s.jpg)
flutter传递值到任意widget(当需要widget嵌套使用需要传递值的时候)
2022-05-17 22:53:44
Java Pattern与Matcher字符串匹配案例详解
2022-03-25 16:07:19
![](https://img.aspxhome.com/file/2023/7/102627_0s.png)
Java基于动态规划法实现求最长公共子序列及最长公共子字符串示例
2021-10-11 22:20:17
![](https://img.aspxhome.com/file/2023/3/90033_0s.png)
解决FeignClient发送post请求异常的问题
2022-08-08 15:55:58
改进c# 代码的五个技巧(二)
2023-01-09 08:57:56
![](https://img.aspxhome.com/file/2023/2/104222_0s.png)
基于Java手写一个好用的FTP操作工具类
2021-06-05 20:10:18
![](https://img.aspxhome.com/file/2023/0/98410_0s.jpg)
Java 实现一个汉诺塔实战练习
2021-12-20 14:49:47
![](https://img.aspxhome.com/file/2023/3/88573_0s.png)
springboot基于Mybatis mysql实现读写分离
2023-11-27 21:42:59
![](https://img.aspxhome.com/file/2023/5/59425_0s.png)
Java客户端调用.NET的WebService实例
2023-11-03 17:22:00
![](https://img.aspxhome.com/file/2023/8/58988_0s.png)
C#实现的文件压缩和解压缩类
2022-11-30 16:08:08
Maven安装及MyEclipse中使用Maven
2023-06-20 04:29:07
![](https://img.aspxhome.com/file/2023/7/69307_0s.png)
JAVA内部类示例详解及练习
2023-04-05 06:42:39
![](https://img.aspxhome.com/file/2023/7/62427_0s.png)
利用Flutter制作经典贪吃蛇游戏
2023-07-21 07:04:13
![](https://img.aspxhome.com/file/2023/4/84724_0s.png)
详解Java中的final关键字
2023-02-20 17:29:50
JavaWeb中获取表单数据及乱码问题的解决方法
2021-11-21 11:03:53
![](https://img.aspxhome.com/file/2023/3/69673_0s.png)