一、如何学习
1.1学会查看官方文档
https://www.elastic.co/guide/index.html
查看Java REST Client
点开一看,里面会有各种API
点进去Java High Level REST Client一看
大概讲了啥,英文不好,去百度翻译一下
可以看一下仓库依赖
依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.1</version>
</dependency>
二、构建项目
2.1使用脚手架,新建项目
2.2填写项目名
3.3添加相关依赖
3.4目录结构
3.5修改配置
添加版本
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
给出代码
ElasticSearchConfig代码
/**
* @program: es7-mo
* @description: 高级客户端注入
* @author: WEN
* @create: 2020-07-24 17:27
**/
//spring 三步骤,
// 1.找对象
// 2.放在sprig中待用
// 3.如果是springboot,先分析源码
@Configuration //创建启动配置 启动时 创建RestHighLevelClient
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}
User实体类
/**
* @program: es7-mo
* @description: 用户实体类
* @author: WEN
* @create: 2020-07-24 17:28
**/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
private String name;
private int age;
}
Es7MoApplicationTests测试类
@SpringBootTest
class Es7MoApplicationTests {
// 面向对象来操作
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
//创建索引 PUT mo1_index
@Test
public void createIndex() throws Exception {
// 1、创建索引请求
CreateIndexRequest request = new CreateIndexRequest("mo1_index");
// 2、客户端执行请求 IndicesClient,请求后获得响应
//CreateIndexResponse createIndexResponse =client.indices().create(request, RequestOptions.DEFAULT);
CreateIndexResponse createIndexResponse = client.indices().create(request,RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
//测试删除索引
@Test
void deleteIndex() throws IOException {
DeleteIndexRequest bnz_index = new DeleteIndexRequest("mo1_index");
AcknowledgedResponse delete = client.indices().delete(bnz_index,RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
//添加文档测试
/** 添加 依赖
* <groupId>com.alibaba</groupId>
* <artifactId>fastjson</artifactId>
* <version>1.2.62</version>
*/
@Test
void addDocument() throws IOException {
//1.创建对象
User user = new User("赵敏", 18);
//2创建请求
IndexRequest request = new IndexRequest("mo1_index");
//3.规则 PUT /mo1_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
//将数据放入请求 json
request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求,获取响应的结果
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
//对应我们命令返回状态created
System.out.println(indexResponse.status());
}
//获取文档 判断是否存在 GET /mo1_index/_doc/1
@Test
void testExists() throws IOException {
GetRequest getRequest = new GetRequest("mo1_index", "1");
//不获取返回_sources上下文
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
// 更新文档的信息
@Test
void testUpdateRequest() throws IOException{
UpdateRequest updateRequest = new UpdateRequest("mo1_index","1");
updateRequest.timeout("1s");
User user = new User("赵敏", 8);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest,RequestOptions.DEFAULT);
System.out.println(updateResponse);
}
// 删除文档记录
@Test
void testDeleteRequest() throws IOException {
DeleteRequest request = new DeleteRequest("mo1_index","1");
request.timeout("1s");
DeleteResponse deleteResponse = client.delete(request,RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}
//批量插入数据
@Test
void bulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("赵敏1",17));
userList.add(new User("赵敏2",18));
userList.add(new User("赵敏3",19));
userList.add(new User("张无忌1",27));
userList.add(new User("张无忌2",28));
userList.add(new User("张无忌3",29));
//批处理请求
for (int i = 0; i <userList.size() ; i++) {
bulkRequest.add(
new IndexRequest("mo1_index")
.id(""+(i+1))
.source(JSON.toJSONString(userList.get(i)),XContentType.JSON));
BulkResponse bulkResponse = client.bulk(bulkRequest,RequestOptions.DEFAULT);
// 是否失败,返回 false 代表 成功
System.out.println(bulkResponse.hasFailures());
}
}
//查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 构建高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!
@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("mo1_index");
//构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.highlighter();
// 查询条件,我们可以使用 QueryBuilders 工具来实现
// QueryBuilders.termQuery 精确
// QueryBuilders.matchAllQuery() 匹配所有
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name","张无忌");
//MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
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());
}
}
}
给出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.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.es7.mo</groupId>
<artifactId>es7-mo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>es7-mo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<!--自定义版本-->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
<dependencies>
<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>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
测试批量删除
浏览查看
参考:https://www.bilibili.com/video/BV17a4y1x7zq?from=search&seid=16093692789696550128