一、环境说明二、实现步骤
一、环境说明- Windows上部署三节点的集群,参考:ElasticSearch Windows集群安装部署elasticsearch版本:7.8.0测试框架:JUnit
创建maven项目
添加es相关依赖,依赖如下:
org.elasticsearch elasticsearch 7.8.0 org.elasticsearch.client elasticsearch-rest-high-level-client 7.8.0 org.apache.logging.log4j log4j-api 2.8.2 org.apache.logging.log4j log4j-core 2.8.2 com.fasterxml.jackson.core jackson-databind 2.9.9 junit junit 4.12
创建ESClientTest测试类,具体代码如下:
package com.suben.es;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suben.es.entity.Student;
import org.apache.http.HttpHost;
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.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.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class ESClientTest {
private static final String INDEX_NAME = "students";
@Test
public void testCreateIndex() throws Exception{
RestHighLevelClient client =
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 1004, "http"),
new HttpHost("localhost", 1005, "http"),
new HttpHost("localhost", 1006, "http"))
);
// 构造索引对象
CreateIndexRequest index001 = new CreateIndexRequest(INDEX_NAME);
// client创建索引
CreateIndexResponse response = client.indices().create(index001, RequestOptions.DEFAULT);
// 查看下释放创建成功
boolean acknowledged = response.isAcknowledged();
// 输出执行结果
System.out.println("创建索引:" + acknowledged);
// 释放资源
client.close();
}
@Test
public void testGetIndex() throws Exception{
RestHighLevelClient client =
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 1004, "http"),
new HttpHost("localhost", 1005, "http"),
new HttpHost("localhost", 1006, "http"))
);
// 构造索引对象
GetIndexRequest index001 = new GetIndexRequest(INDEX_NAME);
// client创建索引
GetIndexResponse response = client.indices().get(index001, RequestOptions.DEFAULT);
// 输出执行结果
System.out.println("创建索引:" + response.getAliases());
System.out.println("创建索引:" + response.getSettings());
System.out.println("创建索引:" + response.getMappings());
// 释放资源
client.close();
}
@Test
public void testDeleteIndex() throws Exception{
RestHighLevelClient client =
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 1004, "http"))
);
// 构造索引对象
DeleteIndexRequest index001 = new DeleteIndexRequest(INDEX_NAME);
// client创建索引
AcknowledgedResponse response = client.indices().delete(index001,RequestOptions.DEFAULT);
// 输出执行结果
System.out.println("删除索引:" + response.isAcknowledged());
// 释放资源
client.close();
}
@Test
public void testAdddocument() throws Exception{
RestHighLevelClient client =
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 1004, "http"))
);
// 新增文档请求对象
IndexRequest indexRequest = new IndexRequest();
// 设置索引及其唯一标识
indexRequest.index(INDEX_NAME).id("1002");
// 构造文档对象
Student student = new Student("李云龙",34,"男");
Student student2 = new Student("张三",34,"男");
Student student3 = new Student("赵丽颖",34,"女");
List list = new ArrayList<>();
list.add(student);
list.add(student2);
list.add(student3);
// 将User对象转成Json字符串
ObjectMapper objectMapper = new ObjectMapper();
String stuJson = objectMapper.writevalueAsString(student);
// 设置文档数据为Student,格式为json
indexRequest.source(stuJson,objectMapper.writevalueAsString(student2),objectMapper.writevalueAsString(student3),
XContentType.JSON);
// 提交新增文档请求(同步模式)
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
// 输出执行结果
System.out.println("新增文档:" + response);
// 释放资源
client.close();
}
@Test
public void testBatchAdddocument() throws Exception{
RestHighLevelClient client =
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 1004, "http"))
);
// 创建批量请求对象
BulkRequest bulkRequest = new BulkRequest();
// 新增文档对象
for (int i = 0; i < 10; i++) {
int uniqueId = 3000 + (i + 1);
if (i % 2 == 0){
bulkRequest.add(new IndexRequest().index(INDEX_NAME).id(String.valueOf(uniqueId)).source(new ObjectMapper().writevalueAsString(new Student("帅哥"+i + "号",28+i,"男")),XContentType.JSON));
}else{
bulkRequest.add(new IndexRequest().index(INDEX_NAME).id(String.valueOf(uniqueId)).source(new ObjectMapper().writevalueAsString(new Student("美女"+i + "号",18+i,"女")),XContentType.JSON));
}
}
// 提交新增文档请求(同步模式)
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
// 输出执行结果
System.out.println("批量新增文档时间:" + response.getTook());
System.out.println("批量新增文档结果:" + response.getItems());
// 释放资源
client.close();
}
@Test
public void testBatchDeletedocument() throws Exception{
RestHighLevelClient client =
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 1004, "http"))
);
// 创建批量请求对象
BulkRequest bulkRequest = new BulkRequest();
// 新增文档对象
for (int i = 0; i < 10; i++) {
int uniqueId = 2000 + (i + 1);
bulkRequest.add(new DeleteRequest().id(String.valueOf(uniqueId)).index(INDEX_NAME));
}
// 提交新增文档请求(同步模式)
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
// 输出执行结果
System.out.println("批量删除文档时间:" + response.getTook());
System.out.println("批量删除文档结果:" + response.getItems());
// 释放资源
client.close();
}
@Test
public void testQueryIndexDatas() throws Exception{
RestHighLevelClient client =
new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 1004, "http"))
);
// 创建查询请求对象
SearchRequest searchRequest = new SearchRequest();
// 指定查询的索引
searchRequest.indices(INDEX_NAME);
// 构造查询索引的请求对象
SearchSourceBuilder requestBuilder = new SearchSourceBuilder();
// 设置查询条件:查询所有,match_all
requestBuilder.query(QueryBuilders.matchAllQuery());
// 设置显示的总条数,默认只显示10条
requestBuilder.size(1000);
// 设置查询请求对象条件,即requestBuilder
searchRequest.source(requestBuilder);
// 提交
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
// 输出执行结果
SearchHits hits = response.getHits();
System.out.println("took:" + response.getTook());
System.out.println("timeout:" + response.isTimedOut());
System.out.println("total:" + hits.getTotalHits());
System.out.println("MaxScore:" + hits.getMaxScore());
System.out.println("hits========>>");
for (SearchHit hit : hits) {
//输出每条查询的结果信息
System.out.println(hit.getSourceAsString());
}
System.out.println("<<========");
// 释放资源
client.close();
}
}
注意事项:由于es默认只显示命中的10条记录,故在代码中需要设置你想显示的总条数,如果不设置,在我的测试数据中总15条,代码执行后,只显示了十条,如下所示:
故需要代码中修改下,上述代码中通过requestBuilder对象设置了1000条,,修改完成后,正常显示,如下:
为了查看日志,可以在resources目录下添加log4j2.xml,内容如下:



