目录
官网API介绍
1、新建maven项目
2、检查elasticsearch依赖的版本
3、配置RestHighLevelClient对象
4、使用springboot-test测试API的使用
官网API介绍
Java API Client
https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html
Java REST Client(rest-high-level-client):
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html
Java REST Client依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
使用对象操作es
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
操作完后关闭连接
client.close();
1、新建maven项目
测试springboot集成elasticsearch的API使用
在新项目的pom文件中添加依赖
<!--导入了elasticsearch依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 引入fastjson依赖,发送elasticsearch的请求体时需要将对象转化为json字符串-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<!--引入lombok插件依赖,生成实体类的get、set等方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--引入springboot测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2、检查elasticsearch依赖的版本
导入elasticsearch依赖后检查org.elasticsearch.client:transport版本号是否与本地版本elasticsearch的版本号一样,不一样进行调整,避免进行elasticsearch连接时出现兼容性问题导致发送的请求有问题
spring-boot-dependencies-2.2.5.RELEASE默认依赖的elasticsearch为6.8.6
此时需要在新建项目的pom文件中指定自己本地的版本号
<!--配置版本信息-->
<properties>
<!--配置java版本-->
<java.version>1.8</java.version>
<!--自定义es版本依赖,保证和本地一致-->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
配置完后刷新Maven
3、配置RestHighLevelClient对象
@Configuration
public class esConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")//有多个elasticsearch实例
));
return client;
}
}
4、使用springboot-test测试API的使用
import com.alibaba.fastjson.JSON;
import com.chen.esapi.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.IndicesClient;
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.client.indices.GetIndexResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class EsApiApplicationTests {
@Resource
private RestHighLevelClient restHighLevelClient;
@Resource
private User user;
//测试创建索引CreateIndexRequest
@Test
public void testCreateIndex() throws IOException {
//1、创建索引请求
CreateIndexRequest request = new CreateIndexRequest("test_index");
//2、执行请求
IndicesClient indicesClient = restHighLevelClient.indices();
CreateIndexResponse createIndexResponse = indicesClient.create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
//测试获取索引GetIndexRequest
@Test
public void testGetIndex() throws IOException {
//1、创建索引请求
GetIndexRequest request = new GetIndexRequest("test_index");
//2、执行请求
IndicesClient indicesClient = restHighLevelClient.indices();
GetIndexResponse getIndexResponse = indicesClient.get(request, RequestOptions.DEFAULT);
System.out.println(getIndexResponse.getIndices());
//判断索引是否存在
boolean exists = indicesClient.exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
//测试删除索引DeleteIndexRequest
@Test
public void testDeleteIndex() throws IOException {
//1、创建索引请求
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("test_index");
//2、执行请求
IndicesClient indicesClient = restHighLevelClient.indices();
AcknowledgedResponse delete = indicesClient.delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
//测试添加文档
@Test
public void testCreateDocument() throws IOException {
//创建对象
user.setId(3);
user.setName("李四");
//创建请求
IndexRequest request = new IndexRequest("test_index");
//设置规则
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
request.source(JSON.toJSONString(user), XContentType.JSON);
//执行请求,并获取响应结果
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
}
//判断文档是否存在
//获取文档
@Test
public void testGetDocument() throws IOException {
//创建请求
GetRequest getRequest = new GetRequest("test_index","1");
//判断文档是否存在
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
//执行请求获取文档信息
GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
String sourceAsString = documentFields.getSourceAsString();
System.out.println(sourceAsString);
}
//更新文档
@Test
public void testUpdateDocument() throws IOException {
//创建请求
UpdateRequest updateRequest = new UpdateRequest("test_index","1");
user.setName("王五");
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update);
}
//删除文档
@Test
public void testDeleteDocument() throws IOException {
//创建请求
DeleteRequest deleteRequest = new DeleteRequest("test_index", "1");
//执行请求
DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}
//批量插入
@Test
public void TestBulkInsert() throws IOException {
//创建请求
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
//设置数据
ArrayList<Object> userlist = new ArrayList<>();
for (int i = 0; i <10 ; i++) {
User user = new User("test user" + i, i);
userlist.add(user);
}
System.out.println(userlist);
for (int i = 0; i < userlist.size(); i++) {
bulkRequest.add(
new IndexRequest("test_index")
.id((i+1)+"")
.source(JSON.toJSONString(userlist.get(i)),XContentType.JSON)
);
}
System.out.println(bulkRequest);
//执行请求
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.status());
}
//查询(重点)
// SearchRequest搜索请求
// SearchSourceBuilder条件构造
// QueryBuilder构造查询参数
@Test
public void testSearch() throws IOException {
SearchRequest request = new SearchRequest("test_index");
//创建查询构造器
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//通过QueryBuilders工具类构建查询条件
//构建term精确查询条件
// TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "user5");
// searchSourceBuilder.query(termQueryBuilder);
//构建mathch查询条件
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "test");
MatchQueryBuilder matchQueryBuilder1 = QueryBuilders.matchQuery("id", "3");
//构建布尔查询
BoolQueryBuilder must = QueryBuilders.boolQuery().must(matchQueryBuilder).must(matchQueryBuilder1);
System.out.println(must);
//使用query封装查询参数
searchSourceBuilder.query(must);
//设置超时时间
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//设置分页
searchSourceBuilder.from(0);
searchSourceBuilder.size(10);
//将查询条件配置到请求中
request.source(searchSourceBuilder);
//执行请求
SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);
System.out.println(searchResponse);
//将结果打印searchResponse.getHits().getHits()
for (SearchHit document :searchResponse.getHits().getHits() ){
System.out.println(document.getSourceAsString());
}
}
}