一. 引入依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.75</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency>
二. 创建ES配置类
package com.lrs.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @作者:刘壬杉
* @创建时间 2022/8/16 16:30
**/
@Configuration
public class EsConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
return restHighLevelClient;
}
}
三. 关于对文档的操作
首先 在测试类中引入RestHighLevelClient对象
@Resource
private RestHighLevelClient client;
其次 准备一个User对象
package com.lrs.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @作者:刘壬杉
* @创建时间 2022/8/16 19:21
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String id;
private String name;
private String address;
private Integer age;
public User(String name, String address, Integer age) {
this.name = name;
this.address = address;
this.age = age;
}
}
3.1 对索引的操作
3.1.1 创建索引
//创建索引
@Test
void testCreateIndex() throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest("test04");
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println(createIndexResponse.isAcknowledged());
}
运行结果:创建成功返回true
3.1.2 删除索引
//删除索引
@Test
void testDeleteIndex() throws Exception{
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test04");
AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
运行结果:删除成功返回true
3.1.3 判断索引是否存在
//判断索引是否存在
@Test
void testExistsIndex() throws Exception{
GetIndexRequest getIndexRequest = new GetIndexRequest("test04");
boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
运行结果:存在返回true,不存在返回false.
3.2 对文档的操作
3.2.1 添加文档
//添加文档
@Test
void testCreateDoc() throws Exception{
IndexRequest indexRequest = new IndexRequest("test04");
indexRequest.id("1");
indexRequest.source(JSON.toJSONString(new User("张三","北京",25)), XContentType.JSON);
IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(index.getResult());
}
运行结果:添加成功返回 CREATED
3.2.2 查询文档----根据id查询
//查询文档 -- id
@Test
void testGetDoc() throws Exception{
GetRequest getRequest = new GetRequest("test04");
getRequest.id("1");
GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(documentFields.getSourceAsMap());
}
运行结果:
3.2.3 判断文档是否存在
//判断文档是否存在
@Test
void testExistsDoc() throws Exception{
GetRequest getRequest = new GetRequest("test04");
getRequest.id("1");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
运行结果:存在返回true,不存在返回false.
3.2.4 删除文档
//删除文档
@Test
void testDeleteDoc() throws Exception{
DeleteRequest deleteRequest = new DeleteRequest("test04");
deleteRequest.id("1");
DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.getResult());
}
运行结果:删除成功返回 DELETED
3.2.5 修改文档
//修改文档
@Test
void testUpdateDoc() throws Exception{
UpdateRequest updateRequest = new UpdateRequest("test04","1");
User user = new User();
user.setName("王五");
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update.getResult());
}
运行结果:修改成功返回 UPDATED
3.2.6 批量添加文档
//批量添加文档
@Test
void testBulk() throws Exception{
BulkRequest bulkRequest = new BulkRequest("test04");
List<User> list = new ArrayList<>();
list.add(new User("1","张三1","北京1",18));
list.add(new User("2","张三2","北京2",19));
list.add(new User("3","张三3","北京3",20));
list.add(new User("4","张三4","北京4",21));
list.add(new User("5","张三5","北京5",22));
list.stream().forEach(item->bulkRequest.add(new IndexRequest().id(item.getId()).source(JSON.toJSONString(item),XContentType.JSON)));
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.hasFailures());
}
运行结果: bulk.hasFailures():判断是否有故障,返回false代表没有故障,添加成功
3.3 复杂查询
复杂查询中包含一个条件对象,条件对象里包含了很多条件,比如 分页,高亮,排序,查询指定列,精准匹配,范围查询等等
//复杂查询
@Test
void testSearch() throws Exception{
SearchRequest searchRequest = new SearchRequest("test04");
//创建条件对象
SearchSourceBuilder builder = new SearchSourceBuilder();
//bool
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("name", "3"))
.should(QueryBuilders.matchQuery("age", 20));
builder.query(boolQueryBuilder);
//分页
builder.from(0);
builder.size(2);
//指定列
String[] includes = {"name","address"};
String[] excludes = {"id"};
builder.fetchSource(includes,null);
//高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("name");
highlightBuilder.preTags("<font>");
highlightBuilder.postTags("</font>");
builder.highlighter(highlightBuilder);
//排序
builder.sort("age", SortOrder.ASC);
searchRequest.source(builder);
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = search.getHits().getHits();
Arrays.stream(hits).forEach(item-> System.out.println(item.getSourceAsMap()));
Arrays.stream(hits).forEach(item-> System.out.println(item.getHighlightFields()));
}
运行结果:文章来源:https://www.toymoban.com/news/detail-421583.html
文章来源地址https://www.toymoban.com/news/detail-421583.html
到了这里,关于Springboot整合Elasticsearch(Es)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!