ElasticSearch+Spring boot -- 简单入门

<!-- json转换 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.73</version>
</dependency>

<!-- ElasticSearch -->
<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-elasticsearch</artifactId>
</dependency>

<!-- 修改版本. 要注意和安装的es版本要对应 -->
<properties>
	<java.version>1.8</java.version>
	<elasticsearch.version>7.9.1</elasticsearch.version>
</properties>

application.properties

# 修改es的默认配置 。 ES源码中默认是 localhost:9200
spring.elasticsearch.rest.uris=http://35.126.68.173:9200
1,ElasticSearch配置类
package com.article.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ElasticSearch配置类
 */
@Configuration
public class ElasticSearchConfig {

	//ElasticSearch服务器的IP地址
	@Value("${es.ip}")
	private String esIp;
	//ElasticSearch服务器的端口
	@Value("${es.port}")
	private Integer esPort;
	//ElasticSearch服务器的协议  http
	@Value("${es.scheme}")
	private String esScheme;
	
	/**
	 * es高级客户端
	 * @return
	 */
	@Bean
	public RestHighLevelClient restHighLevelClient() {
		RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost(esIp, esPort, esScheme)));
		return client;
	}
}
2,Controller

	/**
	 * 搜索文章
	 * @param query 搜索关键字
	 * @param model
	 * @return 搜索结果页面
	 */
	@PostMapping("/search")
	public String search(@RequestParam(name = "query") String query, Model model) {

		// 查询请求
		SearchRequest searchRequest = new SearchRequest(esIndexName);

		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
		//组合查询
		MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery(query, esArticleTitle, esArticleDesc);
		
		sourceBuilder.query(multiMatchQuery);
		sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

		//高亮
		HighlightBuilder highlightBuilder = new HighlightBuilder();
		//设置高亮字段
		highlightBuilder.field(query);
		//关闭多个高亮显示
		highlightBuilder.requireFieldMatch(false);
		//设置标签头
		highlightBuilder.preTags("<span style='color:red'>");
		//设置标签尾
		highlightBuilder.postTags("</span>");
		//设置需要高亮的字段。 不然无法高亮
		highlightBuilder.field(esArticleTitle).field(esArticleDesc);
		
		sourceBuilder.highlighter(highlightBuilder);
		
		searchRequest.source(sourceBuilder);
		try {
			SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			//解析结果
			for (SearchHit documentFields : search.getHits().getHits()) {
				Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
				HighlightField articleTitle = highlightFields.get(esArticleTitle);
				HighlightField articleDesc = highlightFields.get(esArticleDesc);
				Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();

				//解析高亮的字段,将原来的字段换为高亮字段即可
				//标题
				if (articleTitle != null) {
					Text[] fragments = articleTitle.fragments();

					String new_title = "";

					for (Text text : fragments) {
						new_title += text;
					}
					sourceAsMap.put(esArticleTitle, new_title);
				}
				//描述
				if (articleDesc != null) {
					Text[] fragments = articleDesc.fragments();
					
					String new_desc = "";
					for (Text text : fragments) {
						new_desc += text;
					}
					sourceAsMap.put(esArticleDesc, new_desc);
				}
				list.add(sourceAsMap);
			}
			
			//查询到的文章数量
			Long total = search.getHits().getTotalHits().value;

			model.addAttribute("total", total);
			model.addAttribute("esList", list);
			model.addAttribute("query", query);
			return "search";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}



----------------------------------------------------------------------------------------------


可以根据自己的需求,编写操作ElasticSearch的工具类.例如我的插入es和更新es,在插入mysql时候,同时插入es,更新同理
package com.article.util;

import java.io.IOException;

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.article.dto.ArticleTypeTagDTO;
import com.article.mapper.ArticleMapper;
import com.article.mapper.TypeMapper;
import com.article.mapper.UserMapper;

/**
 * 往ES中执行插入或更新操作
 * @author June
 * @date 2020/09/21
 * @version V1.0
 */
@Component
public class ElasticSearchOptUtils {

	@Autowired
	private RestHighLevelClient restHighLevelClient;
	@Autowired
	private TypeMapper typeMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private ArticleMapper articleMapper;

	//ElasticSearch中的索引名, 相当于数据库名
	@Value("${es.indexName}")
	private String esIndexName;

	/**
	 * 往ES中插入数据
	 * @param dto
	 */
	public void insert(ArticleTypeTagDTO dto) {
		GetIndexRequest getIndexRequest = new GetIndexRequest(esIndexName);
		try {
			//判断索引是否存在
			boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
			if (!exists) {
				//如果不存在就创建
				CreateIndexRequest createIndexRequest = new CreateIndexRequest(esIndexName);
				restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
			}
			//添加字段为null的数据
			user.setPassword("123");
			user.setAvatar("cat.jpg");
			
			IndexRequest indexRequest = new IndexRequest(esIndexName);
			//设置id
			indexRequest.id(Long.toString(user.getId()));
			//设置数据
			indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
			//执行存入请求
			restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过ID更新ES中的数据
	 * @param user
	 * @param id 用户ID
	 */
	public void update(ArticleTypeTagDTO dto, Long id) {
		UpdateRequest updateRequest = new UpdateRequest(esIndexName, Long.toString(id));
		updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
		try {
			//执行更新请求
			restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
插入或更新文章
@Transactional
	@Override
	public void saveOrUpdate(ArticleTypeTagDTO dto) {

		//字符串标签ids转换为列表
		List<Long> tagIdList = StringAndListConvertUtils.toList(dto.getTagIds());

		Long articleId = dto.getId();
		if (articleId == null) {
			//插入操作
			dto.setCreateTime(new Date(System.currentTimeMillis()));
			dto.setUpdateTime(new Date(System.currentTimeMillis()));
			dto.setViewCount(0);
			dto.setCommentCount(0);
			
			//往mysql中插入文章
			articleMapper.save(dto);
			//插入article_tag中间表
			for (Long tagId : tagIdList) {
				tagMapper.saveArticleAndTag(dto.getId(), tagId);
			}
			
			Long id = dto.getId();
			//初始化redis缓存数据库中的点赞数
			redisUtil.hPut("article", "likeCount" + id, Integer.toString(0));
			
			//往ElasticSearch中插入查询时候搜索的字段内容【插入标题和描述】
			esOptUtils.insert(dto);
		} else {
			//更新操作
			Article b = articleMapper.findById(articleId);
			BeanUtils.copyProperties(dto, b);
			b.setUpdateTime(new Date(System.currentTimeMillis()));
			//更新文章
			articleMapper.update(b);
			//删除该文章的article_tag中间表数据,重新插入article_tag中间表
			tagMapper.deleteByArticleId(articleId);
			for (Long tagId : tagIdList) {
				tagMapper.saveArticleAndTag(articleId, tagId);
			}
			
			//根据id更新lasticSearch中的内容【更新标题和描述】
			esOptUtils.update(dto, articleId);
		}
	}





搜罗的一些资料

ElasticSearch 笔记 1
实战 ➡ 仿京东搜索
https://blog.csdn.net/mgdj25/article/details/105740191

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值