最近因为需求,然后自学了es,下面把学习成果分享一下,希望可以帮助es才入门的小伙伴,话不多说,下面开始。
在开始之前,需要有es,官网下载比较慢,下面是我下载的es7.6.1,拿走不谢
es-7.6.1百度网盘
提取码:syfk
spring-boot集成es 7.6.1
1)创建一个springboot项目,项目创建比较简单,下面截图是创建项目需要引入的依赖
2)因为spring-boot自带的es版本还是6.xx,所以需要更改一下版本,在pom.xml文件中,添加
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
3)引入es高级客户端依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.1</version>
</dependency>
关于es客户端介绍,最好在官网查看
4)配置,新建一个配置类,下面是我的配置类
package com.study.es_study.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@SpringBootConfiguration
public class ElasticSearchConfig {
//在spring容器中放入RestHighLevelClient,使用的时候直接注入就可以了
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")));
return restHighLevelClient;
}
}
常见API使用
在springboot的test里面测常用的api,在开始之前,在测试类中注入RestHighLevelClient
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
关于索引的操作
1.创建索引
@Test
public void contextLoadTest() throws IOException {
//创建索引请求
CreateIndexRequest request = new CreateIndexRequest("dome_one");
System.out.println(client);
//这里是通过客户端,然后传递请求, RequestOptions.DEFAULT(这个是默认的,是es里面的,可以查看源码)
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response);
}
2.查询索引是否存在
@Test
public void existRequest() throws IOException {
//创建请求
GetIndexRequest re = new GetIndexRequest("dome_one");
boolean exists = client.indices().exists(re,RequestOptions.DEFAULT);
System.out.println(exists);
}
3.删除索引
@Test
public void deleteRequest() throws IOException {
//创建删除索引请求
DeleteIndexRequest request = new DeleteIndexRequest("dome_one");
//通过客户端把请求提交
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete);
}
总结:
①关于索引相关的操作,比较好理解,对索引进行什么操作,则建立相应的请求
②通过es的客户端api,client.indices():获取关于indexClient,来得到对index操作的权力
③在②的基础上,indexClient.(相应操作)
文档crud
1.添加
@Test
public void addDocumentTest() throws IOException {
//创建请求连接
IndexRequest request = new IndexRequest("dome_one");
//创建要添加的信息
User user = new User("大鹏鸟",6);
//通过rest高级客户端添加信息
request.id("1"); //自定义id,不自定义则随机生成
request.timeout("10s"); //请求超时不执行
//把要添加的信息放入请求中,XContentType.JSON(指定信息的类型)
request.source(JSON.toJSONString(user), XContentType.JSON);
//通过客户端传递求情
IndexResponse responseResult = client.index(request, RequestOptions.DEFAULT);
System.out.println(responseResult.toString());
System.out.println(responseResult.status());
}
2.修改
@Test
public void updateDocument() throws IOException {
//创建修改请求,请求中指定索引,修改id
UpdateRequest request = new UpdateRequest("dome_one","1");
request.timeout("5s");
User user = new User("大鹏鸟学java", 10);
//es原生api中有_doc,这里在修改的时候调用doc(),把要修改的信息放入请求中
request.doc(JSON.toJSONString(user),XContentType.JSON);
request.fetchSource(true);//修改之后获取结果
UpdateResponse update = client.update(request, RequestOptions.DEFAULT);
System.out.println(update.toString());
System.out.println(update.getIndex());
System.out.println(update.getGetResult());
System.out.println(update.status());
}
3.删除
public void deleteDocument() throws IOException {
//创建删除请求,指定索引和删除的id
DeleteRequest request = new DeleteRequest("dome_one","1");
DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
System.out.println(delete.status());
System.out.println(delete.toString());
}
4.查询
@Test
public void queryDocument() throws IOException {
//查询请求
GetRequest request = new GetRequest("dome_one","wqFN7XMBSotzIjY682h-");
GetResponse response = client.get(request, RequestOptions.DEFAULT);
System.out.println(response.getSource());
}
批量添加,搜索,高亮查询
1.批量添加(删除修改类型)
@Test
public void bulkDocument() throws IOException {
//执行批量操作的请求
BulkRequest request = new BulkRequest("dome_one");
request.timeout("10s");
request.estimatedSizeInBytes();
List<User> userList = new ArrayList<User>();
User u1 = new User("张三", 1);
User u2 = new User("张21", 221);
User u3 = new User("张1", 21);
User u4 = new User("张21三", 21);
User u5 = new User("13张21三", 31);
User u6 = new User("32张21三", 21);
User u7 = new User("31张三", 1);
userList.add(u1);
userList.add(u2);
userList.add(u3);
userList.add(u4);
userList.add(u4);
userList.add(u5);
userList.add(u6);
userList.add(u7);
for (int i =0 ; i < 7 ; i++){
//通过批量请求,依次放入单个请求,类似入数据库的批量操作
request.add(new IndexRequest()
.source(JSON.toJSONString(userList.get(i)),XContentType.JSON));
}
//客户端执行批量操作
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.status());
}
2.搜索
@Test
public void searchDocument() throws IOException {
//搜索请求
SearchRequest request = new SearchRequest("dome_one");
//请求条件构建器,这里和mybatis中的自定义查询有点类型
SearchSourceBuilder builder = new SearchSourceBuilder();
//匹配所有
// MatchAllQueryBuilder allQuery = QueryBuilders.matchAllQuery();
/*
*精确查询
*QueryBuilders:查询工具,用它查询比较方便
*/
TermQueryBuilder termQuery = QueryBuilders.termQuery("name", "张三");
//把查询添加放入查询构造器中
builder.query(termQuery);
//把查询添加放入请求中
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//打印查询的信息
for (SearchHit hit : response.getHits().getHits()) {
System.out.println(hit.getSourceAsMap());
}
}
3.高亮查询
@Test
public void highSearch() throws IOException {
//创建查询请求
SearchRequest request = new SearchRequest("dome_one");
//
SearchSourceBuilder builder = new SearchSourceBuilder();
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张三");
builder.query(matchQueryBuilder);
HighlightBuilder highlighter = new HighlightBuilder();
highlighter.field("name",1);
highlighter.preTags("<em style='color:red>'");
highlighter.postTags("</em>");
builder.highlighter(highlighter);
request.source(builder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
System.out.println(response.getHits().getCollapseValues());
System.out.println(response.getAggregations());
System.out.println(response.getHits().getSortFields());
System.out.println(response.getHits().getHits().length);
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit:hits) {
System.out.println(hit.toString());
}
System.out.println();
System.out.println(response.getHits().getAt(0));
System.out.println(response.toString());
System.out.println(response.getTook().toString());
System.out.println(response.status());
}
至此es的常用操作就没问题了,能满足一般需求,深入学习还是需要查看官网文档。
原创不易,转发请标明文章出处,谢谢