springBoot集成es,和api
1.创建新springboot项目
//选中默认springboot版本 + NoSql 中的 es
//注意项目使用java8
//进入项目后,调整 项目使用 java1.8 + javascript EC6
//在pom 文件中 注意 设置使用的es版本、
<properties>
<java.version>1.8</java.version>
<!--自定义版本依赖-->
<elasticsearch.version>7.6.1 </elasticsearch.version>
</properties>
//准备 vue.js 和 axios.js
cnpm install vue
cnpm install axios
2.注意 springboot版本中es的版本 , 和本地版本 是否一致
//创建RestHighLevelClient 客户端对象。 Config文件
// 1.找spring对象
// 2.放到spring中
@Configuration //xml
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client =new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
return client;
}
}
3.构建实体对象
package com.sinsoft.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/**
* @Auther Qianxy
* @Date 2020/7/26
*/
//AllArgsConstructor 有参
//NoArgsConstructor 无参
//Component 注入到 spring 中
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
private String name;
private int age;
}
4.自定义es简单API
package com.sinsoft;
import com.alibaba.fastjson.JSON;
import com.sinsoft.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class TonyEsApiApplicationTests {
//Qualifier 指定
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
@Test
void contextLoads() throws IOException {
//1.创建索引请求
CreateIndexRequest request = new CreateIndexRequest("kuang_index1");
//2.执行请求 indicesClient,请求后获得响应
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
//获取索引的类型
System.out.println(createIndexResponse.index());
//
System.out.println(createIndexResponse);
}
//获取 索引
@Test
void testExistIndex () throws IOException{
//获取 索引请求、
GetIndexRequest request = new GetIndexRequest("kuang_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
//删除索引
@Test
void testDeleIndex () throws IOException{
//删除
DeleteIndexRequest request = new DeleteIndexRequest("kuang_index1");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
//添加文档
@Test
void testAddDocument()throws IOException{
//创建对象
User user = new User("狂神说", 3);
//创建请求
IndexRequest request = new IndexRequest("kuang_index");
//规则 put /kaung_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
//将请求数据放在 json
request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求 , 获取响应的结果
IndexResponse index = client.index(request, RequestOptions.DEFAULT);
System.out.println(index.toString());
System.out.println(index.status());
}
//获取文档
@Test
void testIsExist() throws IOException{
GetRequest getRequest = new GetRequest("kuang_index", "1");
//getRequest
//getRequest.fetchSourceContext(new FetchSourceContext(false));
//getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
//获得文档信息
@Test
void testGetDocument() throws IOException{
GetRequest getRequest = new GetRequest("kuang_index","1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.toString());
System.out.println(getResponse);
}
//更新文档
@Test
void testUpDateRequest() throws IOException{
UpdateRequest updateRequest = new UpdateRequest("kuang_index", "1");
updateRequest.timeout("1s");
User user = new User("qianaa1",21);
// kuang_index/_doc/1/_update
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}
//删除文档记录
@Test
void testDeleteRequest() throws IOException{
DeleteRequest request = new DeleteRequest("kuang_index", "1");
request.timeout("1s");
DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
System.out.println(delete.status());
}
//批量插入数据
@Test
void testBulkRequest() throws IOException{
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userArrayList = new ArrayList<>();
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
//批处理请求
for (int i = 0; i <userArrayList.size() ; i++) {
bulkRequest.add(
new IndexRequest("kuang_index")
.id(""+(i+1))
.source(userArrayList.get(i),XContentType.JSON)
);
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
//是否失败 false 就是没有失败
System.out.println(bulkResponse.hasFailures());
}
//查询
// 1.SearchRequest 构建请求
// 2.SearchSourceBuilder 条件构造
// 3.TermQueryBuilder 精确条件构造 MatchAllQueryBuilder 全部查询
// 4.SearchResponse client.search() 执行客户端请求
// 5.searchResponse.getHits().getHits() 解析封装的Json数据,需要getHits两次
@Test
void testSeach() throws IOException{
SearchRequest searchRequest = new SearchRequest("kuang_index");
//构建搜索
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//高亮 API
//searchSourceBuilder.highlighter();
//精确搜索
TermQueryBuilder termQueryBuilder = new TermQueryBuilder("name","qianaa1");
//全部查询,匹配索引
//MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
//执行精确查询
searchSourceBuilder.query(termQueryBuilder);
//分页 有默认值
//searchSourceBuilder.from();
//searchSourceBuilder.size();
//设定 过期时间
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//将构建索引 放入请求
searchRequest.source(searchSourceBuilder);
//客户端 进行查询
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// es将客户端查询数据 分装在Hits
// searchResponse.getHits() 获取的java对象,json工具不能解析
//searchResponse.getHits().getHits() 获取可以解析json对象
System.out.println(JSON.toJSONString(searchResponse.getHits().getHits()));
System.out.println("===================================================");
//展示对象
for (SearchHit documentFields:searchResponse.getHits().getHits() ) {
System.out.println(documentFields.getSourceAsMap());
}
}
}

浙公网安备 33010602011771号