- 掌握配置文件的编写熟练掌握使用es的高级客户端对索引和文档的操作使用ElasticsearchRepository对数据库进行交互使用接口或者高级客户端完成对数据的精确查询和高亮查询
你要知道:
提示:本人使用的spring boot版本为2.5.3,底层所依赖的es版本为7.12.1
导入依赖
编写配置文件org.springframework.boot spring-boot-starter-web mysql mysql-connector-java 8.0.16 org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.0 org.springframework.boot spring-boot-starter-data-elasticsearch com.alibaba fastjson 1.2.76
public class EsCoonfig{
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.31.79", 9200, "http")));
return client;
}
}
高级客户端对索引以及文档的操作
@Autowired private RestHighLevelClient client;创建索引
//创建索引
@Test
public void testCreateIndex(){
//创建索引请求
CreateIndexRequest request=new CreateIndexRequest("moyi");
//客户端执行请求,请求后获得响应
CreateIndexResponse response=client.indeices().create(request,RequestOptions.DEFAULT);
}
判断索引是否存在
//获取索引,判断索引是否存在
@Test
public void testGetIndex() throws IOException {
//创建获取索引的请求
GetIndexRequest request = new GetIndexRequest();
request.indices("moyi");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
删除索引
//删除索引
@Test
public void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("moyi");
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
创建文档
public class User{
private String name;
private int age;
}
@Test
public void testAdddocument() thrwos IOException{
//创建对象
User user=new User("moyi",20)
//创建请求
IndexRequest request=new IndexRequest();
//添加规则,将user对象添加到moyi索引下,id设置为1,如果不设置id则随机生成uuid
request.index("moyi").id("1");
//将数据放入请求中,使用fastjson将user对象转换为json字符串
request.source(JSON.toJSONString(user),XContentType.JSON);
//客户端发送请求,获取响应的结果
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//获取响应的结果
System.out.println(response.getResult());
//获取响应的状态
System.out.println(response.status());
}
判断文档是否存在
//判断文档是否存在
@Test
public void testIsExists() throws IOException {
GetRequest request = new GetRequest("moyi", "1");
//不获取返回的_source的上下文
request.fetchSourceContext(new FetchSourceContext(false));
request.storedFields("_none_");
boolean exists = client.exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
获取文档的信息
//获取文档信息
@Test
public void testGetdocument() throws IOException {
GetRequest request = new GetRequest("moyi", "1");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSourceAsString());//打印文档内容
System.out.println(response);
}
更新文档记录
@Test
public void testUpdatedocument() throws IOException {
UpdateRequest request = new UpdateRequest("moyi", "1");
//设置超时时间
request.timeout(Timevalue.timevalueSeconds(1));
User user = new User("时光之境", 24);
request.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println(response.status());
System.out.println(response.getResult());
}
删除文档记录
//删除文档记录
@Test
public void testDeletedocument() throws IOException {
DeleteRequest request = new DeleteRequest("moyi", "1");
//设置超时时间
request.timeout(Timevalue.timevalueSeconds(1));
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
System.out.println(response.status());
}
批量插入数据
@Test
public void testBulkRequest() throws IOException {
BulkRequest request = new BulkRequest();
request.timeout(Timevalue.timevalueSeconds(10));
List users = new ArrayList<>();
users.add(new User("zhangsan", 10));
users.add(new User("lisi", 11));
users.add(new User("wangwu", 12));
users.add(new User("zhaoliu", 13));
for (int i = 0; i < users.size(); i++) {
request.add(
new IndexRequest("moyi")
.id("" + (i + 1))
.source(JSON.toJSONString(users.get(i)), XContentType.JSON)
);
}
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
//判断是否执行失败,false表示成功插入
System.out.println(response.hasFailures());
}
查询文档
@Test
public void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("moyi");
//构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//构建查询条件,通过QueryBuilders工具实现
TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "zhangsan");
sourceBuilder.query(termQuery);
//设置超时时间
sourceBuilder.timeout(Timevalue.timevalueSeconds(60));
searchRequest.source(sourceBuilder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(response.getHits().toString());
System.out.println("======================================================");
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsMap());
}
}
使用ElasticsearchRepository将数据库的数据存入到es中
创建一个entity类
package com.moyi.nowcoder.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Setting;
import java.util.Date;
@document(indexName = "discusspost")//设置索引名称
@Setting(
shards = 6, //设置分片
replicas = 3 //设置副本
)
public class DiscussPost {
@Id
private Integer id;
@Field(type = FieldType.Integer)
private Integer userid;
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart_word")
private String title;
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart_word")
private String content;
@Field(type = FieldType.Integer)
private Integer type=0;
@Field(type = FieldType.Integer)
private Integer status=0;
@Field(type = FieldType.Date)
private Date createTime;
@Field(type = FieldType.Integer)
private Integer commentCount=0;
@Field(type = FieldType.Double)
private double score;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getCommentCount() {
return commentCount;
}
public void setCommentCount(Integer commentCount) {
this.commentCount = commentCount;
}
public double getScore() {
return score;
}
public void setScore(Double score) {
this.score = score;
}
public DiscussPost(int id, int userid, String title, String content, int type, int status, Date createTime, int commentCount, double score) {
this.id = id;
this.userid = userid;
this.title = title;
this.content = content;
this.type = type;
this.status = status;
this.createTime = createTime;
this.commentCount = commentCount;
this.score = score;
}
public DiscussPost() {
}
@Override
public String toString() {
return "DiscussPost{" +
"id=" + id +
", userid=" + userid +
", title='" + title + ''' +
", content='" + content + ''' +
", type=" + type +
", status=" + status +
", createTime=" + createTime +
", commentCount=" + commentCount +
", score=" + score +
'}';
}
}
定义DiscussPostRepository接口
package com.moyi.nowcoder.dao.elasticsearch; import com.moyi.nowcoder.entity.DiscussPost; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; @Repository public interface DiscussPostRepository extends ElasticsearchRepository保存或修改数据{ }
@Autowired
private DiscussPostRepository postRepository;
@Autowired
private RestHighLevelClient restHighLevelClient;
public void save(DiscussPost discussPost){
postRepository.save(discussPost);
}
根据id删除数据
public void delete(Integer id){
postRepository.deleteById(id);
}
高亮查询
public Listsearch(String keyword,int start,int limit) throws IOException { //构建查询 SearchRequest request = new SearchRequest("discusspost"); //构建查询条件 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder() .query(QueryBuilders.multiMatchQuery(keyword,"title","content"))//多字段匹配 .sort(SortBuilders.fieldSort("type").order(SortOrder.DESC))//根据类型排序 .sort(SortBuilders.fieldSort("score").order(SortOrder.DESC))//根据得分排序 .sort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))//根据时间排序 .from(start).size(limit) .highlighter(new HighlightBuilder().field("title").preTags("").postTags("").requireFieldMatch(false))//高亮字段用em标签包裹,且关闭多个高亮 .highlighter(new HighlightBuilder().field("content").preTags("").postTags("").requireFieldMatch(false)); request.source(sourceBuilder); SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT); SearchHit[] hits = searchResponse.getHits().getHits(); List list=new ArrayList<>(); for (SearchHit hit : hits) { //获取高亮字段 Map highlightFields = hit.getHighlightFields(); //解析高亮字段 Map sourceAsMap = hit.getSourceAsMap(); HighlightField title = highlightFields.get("title"); if (title != null) { Text[] fragments = title.getFragments(); String newTitle=""; newTitle+=title; sourceAsMap.put("title",newTitle); } HighlightField content = highlightFields.get("content"); if (content != null) { Text[] fragments = content.getFragments(); String newContent=""; newContent+=content; sourceAsMap.put("content",newContent); } list.add(JSONObject.parseObject(hit.getSourceAsString(),DiscussPost.class)); } return list; }



