这里整合的是Java High Level REST Client
要求会elasticsearch的基本命令,我下面不会解释和Kibana里面相同字段的意思
环境:
- SpringBoot 2.3.4.RELEASE
- ElsticSearch7.6.1
SpringBoot
1、建一个SpringBoot项目,可以勾选elasticsearch、lombok、web等
2、添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
3、添加完成后一定要保证添加的ES和本地的版本保持一致,如果不一样要自定义版本
<!--自己定义es版本依赖,保证和本地一致-->
<elasticsearch.version>7.6.1</elasticsearch.version>
初始化
一个RestHighLevelClient实例需要一个REST low-level client builder 将按以下方式建造:
//建一个config包,类名为ElasticSearchClientConfig
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}
以下的所有操作全部在SpringBoot的test里面测试
注入客户端对象
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
到这里差不多实现了基本的整合,下面开始说说关于索引的基本操作
关于索引的API操作
由于下面的操作基本都用到了Json,所以还要加上一个fastjson依赖,方便使用
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
创建索引
1、创建索引请求 CreateIndexRequest
2、客户端执行请求 client.indices()
3、执行的参数使用默认的RequestOptions.DEFAULT
@Test
void testCreateIndex() throws IOException {
//1、创建索引请求
// 创建索引为 wu_index 的索引
CreateIndexRequest request = new CreateIndexRequest("wu_index");
//2、客户端执行请求 indicesClient 请求后获得响应
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.index());
}
获取索引
只能判断其是否存在
1、获取索引请求 GetIndexRequest
2、客户端执行请求
3、执行的参数使用默认的RequestOptions.DEFAULT
@Test
void testExistsIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("wu_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
删除索引
1、获取删除索引请求
2、客户端执行
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("wu_index");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
关于文档的API操作
创建实体类
建一个pojo包,包名为User
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
添加文档
@Test
void testAddDocument() throws IOException {
//1、创建对象
User user1 = new User("张三", 20);
//2、创建请求
IndexRequest request = new IndexRequest("wu_index");
//3、规则 PUT wu_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
//4、将我们的数据放入请求
request.source(JSON.toJSONString(user1), XContentType.JSON);
//5、客户端发送请求,获取响应的结果
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
//输出响应回来的结果
System.out.println(indexResponse.toString());
//查看当前文档的状态 CREATED
System.out.println(indexResponse.status());
}
获取文档,先判断其是否存在
@Test
void testIsExists() throws IOException {
//1、创建获取文档请求
GetRequest request = new GetRequest("wu_index", "1");
//设置不获取返回的 _source 的上下文
request.fetchSourceContext(new FetchSourceContext(false));
//2、客户端执行请求
boolean exists = client.exists(request, RequestOptions.DEFAULT);
//输出是否存在
System.out.println(exists);
}
获取文档信息
@Test
void testGetDocument() throws IOException {
//1、创建获取文档请求
GetRequest request = new GetRequest("wu_index", "1");
//2、客户端执行请求
GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
//返回当前文档的内容
System.out.println(getResponse.getSourceAsString());
//返回所有的信息
System.out.println(getResponse);
}
和我们开始学命令输出的信息一摸一样
更新文档
@Test
void testUpdateDocument() throws IOException {
//1、获取更新文档请求
UpdateRequest updateRequest = new UpdateRequest("wu_index", "1");
//2、设置超时时间,也可以不设置
updateRequest.timeout(TimeValue.timeValueSeconds(1));
//3、创建一个对象用来更新
User user = new User("李四", 18);
//4、把我们要更新的对象用JSON转成Stirng,然后后面指出传进去的为Json,最后放进doc里面
updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
//5、客户端执行请求
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
//输出当前文档操作的状态 OK
System.out.println(updateResponse.status());
}
删除文档
void testDeleteDocument() throws IOException {
//1、获取更新文档请求
DeleteRequest deleteRequest = new DeleteRequest("wu_index", "1");
//2、设置超时
deleteRequest.timeout(TimeValue.timeValueSeconds(1));
//3、客户端执行请求
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
// OK
System.out.println(deleteResponse.status());
}
批量插入文档
@Test
void testBulkRequest() throws IOException {
// 1、创建批量操作请求
BulkRequest bulkRequest = new BulkRequest();
//2、设置超时
bulkRequest.timeout(TimeValue.timeValueSeconds(10));
//3、用list装User对象
ArrayList<User> userList = new ArrayList<>();
//名字我为什么不用中文呢?因为在精确查询的时候会被分词器分词,除非你在自己的字典里面添加下面的几个字段
userList.add(new User("zhangsan1", 20));
userList.add(new User("zhangsan2", 20));
userList.add(new User("zhangsan3", 20));
userList.add(new User("zhangsan4", 20));
userList.add(new User("zhangsan5", 20));
userList.add(new User("zhangsan6", 20));
userList.add(new User("zhangsan7", 20));
userList.add(new User("zhangsan8", 20));
userList.add(new User("zhangsan9", 20));
//4、批量处理请求
for (int i = 0; i < userList.size(); i++) {
//5、执行添加
bulkRequest.add(
new IndexRequest("wu_index")
.id("" + (i + 1))
.source(JSON.toJSONString(userList.get(i)), XContentType.JSON)
);
//批量删除直接改变就行
// bulkRequest.add(new DeleteRequest("wu_index", "" + (i + 1)));
}
//6、客人护短执行操作
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());//是否执行失败 FALSE : 成功 TRUE : 失败
}
批量查询
@Test
void testBulkSearch() throws IOException {
//1、获取查询请求
SearchRequest searchRequest = new SearchRequest("wu_index");
//2、创建搜索条件 SearchSourceBuilder
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//QueryBuilders.termQuery 精确匹配
//QueryBuilders.matchAllQuery() 模糊匹配
//HighlightBuilder 构建高亮
//3、查询条件 ,我们可以使用 QueryBuilders 工具类来快速匹配
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zhangsan1");
//4、然后把查询条件放进 搜索条件 sourceBuilder 里面
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//5、把搜索条件添加到搜索请求中
searchRequest.source(sourceBuilder);
//6、客户端执行请求
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//hits 应该熟悉吧? 它是返回来的一个对象
System.out.println(JSON.toJSONString(searchResponse.getHits()));
System.out.println("=============================================");
//遍历下这个返回来的所有对象
for (SearchHit documentFields : searchResponse.getHits().getHits()) {
System.out.println(documentFields.getSourceAsMap());
}
}
更多复杂的操作还请看官网,上面只是最基本的