导入坐标文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>li.chen.com</groupId>
<artifactId>es-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>es-api</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<!--自定义es的依赖,保证和本地一致-->
<elasticsearch.version>7.11.1</elasticsearch.version>
</properties>
<dependencies>
<!--导入elasticsearch-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<!--json格式-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.59</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
es配置文件
package li.chen.com.esapi.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @ClassName: ElasticSearchClientConfig
* @Description es客户端
**/
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")
)
);
return client;
}
}
启动类
package li.chen.com.esapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EsApiApplication {
public static void main(String[] args) {
SpringApplication.run(EsApiApplication.class, args);
}
}
测试类(操作方法)
package li.chen.com.esapi;
import com.alibaba.fastjson.JSON;
import li.chen.com.esapi.pojo.User;
import li.chen.com.esapi.utils.ESconst;
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.*;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class EsApiApplicationTests {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
//创建索引 (等同于es的 PUT test_index )
@Test
void testCreateIndex() throws IOException {
// 1创建索引请求
CreateIndexRequest request = new CreateIndexRequest("test_index");
// 2 客户端执行请求 IndicesClient ;请求后获得响应
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
//获取索引 (等同于es的 GET test_index ;只能判断其是否存在)
@Test
void testExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("test_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
// 删除索引
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("test_index");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete);
}
// 测试添加文档及数据(PUT /test_index/_doc/1 {json请求体} ) ;将前端数据封装为实体类对象
@Test
void testAddDocument() throws IOException {
//创建对象
User user = new User("张三", 12);
//创建请求
IndexRequest request = new IndexRequest("test_index");
//设置规则 PUT /test_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s"); //过期时间1s
//将数据放入请求 json格式
IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求,获取响应的结果
IndexResponse index = client.index(request, RequestOptions.DEFAULT);
System.out.println(index); //result=created 为新增
}
// 获取文档 ,判断是否存在 (GET test_index)
@Test
void testExistsDocument() throws IOException {
GetRequest getRequest = new GetRequest("test_index", "1");
// 不配置_source 的上下文;效率更高
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
/*
true
*/
}
//获取文档的信息 (GET /test_index/_doc/1 )
@Test
void testExistsDocumentDes() throws IOException {
GetRequest getRequest = new GetRequest("test_index", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString()); //打印文档内容
System.out.println(getResponse); //返回全部内容,和命令一直
/*
{"age":12,"name":"张三"}
{"_index":"test_index","_type":"_doc","_id":"1","_version":1,"_seq_no":0,"_primary_term":1,"found":true,"_source":{"age":12,"name":"张三"}}
*/
}
//更新文档的信息
@Test
void testGetDocument() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("test_index", "1");
updateRequest.timeout("1s");
User user = new User("李四", 11);
updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
/*
OK
*/
}
// 删除文档记录
@Test
void testDeleteRequests() throws IOException {
DeleteRequest request = new DeleteRequest("test_index", "1");
request.timeout("1s"); //超时时间
DeleteResponse deleteResponse = client.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
/*
OK
*/
}
// 批量插入数据!
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("张三", 11));
userList.add(new User("张四", 12));
userList.add(new User("张五", 13));
userList.add(new User("张六", 14));
userList.add(new User("张七", 15));
userList.add(new User("张八", 16));
userList.add(new User("张九", 17));
userList.add(new User("张十", 18));
userList.add(new User("少司命", 15));
for (int i = 0; i < userList.size(); i++) {
bulkRequest.add(new IndexRequest("test_index")
.id("" + (i + 1)) //不设置会自动生成随机id(很长),有些影响性能
.source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures()); //是否失败;false代表成功!
}
// 查询
@Test
void testSearchAll() throws IOException {
SearchRequest searchRequest = new SearchRequest(ESconst.ES_INDEX);
//构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//查询条件 QueryBuilders 工具
//查询所有
MatchAllQueryBuilder allQueryBuilder = QueryBuilders.matchAllQuery();
sourceBuilder.timeout(new TimeValue(60, TimeUnit.NANOSECONDS));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse.getHits())); //获取对象
System.out.println("+++++++++++++++++++++++");
for (SearchHit documentFields : searchResponse.getHits().getHits()) {
System.out.println(documentFields.getSourceAsMap());
}
}
//精确匹配 termQuery;与matchQuery区别
@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest(ESconst.ES_INDEX);
//构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//查询条件 QueryBuilders 工具
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", "张三");
/*
//精确匹配
termQuery:不会对搜索词进行分词处理,而是作为一个整体与目标字段进行匹配,若完全匹配,则可查询到。
中文查询还是将其进行了分词;故 需要写成 name.keyword ;否则使用 name查询 ,查询结果显示为空
//查询所有匹配
matchQuery:会将搜索词分词,再与目标查询字段进行匹配,若分词中的任意一个词与目标字段匹配上,则可查询到。
会查出所有数据
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张三");
*/
sourceBuilder.query(termQueryBuilder);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse.getHits())); //获取对象
}
}

本文介绍了如何在SpringBoot项目中整合Elasticsearch,通过添加依赖、配置文件设置、编写启动类以及测试类实现数据的增删改查操作。
2067

被折叠的 条评论
为什么被折叠?



