我们应该开始连接我们的Java程序来写
1,新建一个 EmptyProject 模块
2,新建一个Springboot 项目。此处省略。
建完后的目录结构。
注意:此时我们的es 的版本可能与我们本地的版本不一致
我本地的是7.6.1
这里我们需要再pom.xml 里面修改一下版本的问题
完整的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.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.es</groupId>
<artifactId>jj-es-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jj-es-api</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<!-- 自定义我们的es 版本-->
<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.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
下载完依赖后查看,我们的版本和本地一致了!这样才能保证可以连接成功!
自定义我们的ElasticSearch 配置类
package com.es.jjesapi.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;
/**
* @author fjj
* @date 2021/4/9 22:34
*/
//加入注解
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1",9200,"http")));
return client;
}
}
大概查看一下 Springboot 中 集成 ElasticSearch 的源码 简单分析
核心的三个 。。。不过我不怎么能看懂。。
简单测试Api
创建索引
package com.es.jjesapi;
import com.es.jjesapi.config.ElasticsearchConfig;
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.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;
@SpringBootTest
class JjEsApiApplicationTests {
//注入我们的测试类
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
@Test
void contextLoads() {
}
@Test
//创建索引,相当与之前的命令行的put index
public void CreateIndex() throws IOException {
//创建索引的请求
CreateIndexRequest request = new CreateIndexRequest("fjj-index");
//客户端执行
IndicesClient indices = client.indices();
//创建
CreateIndexResponse response = indices.create(request, RequestOptions.DEFAULT);
//输出
System.out.println("response = " + response);
}
}
结果
**获取索引 **
@Test
//获取索引,其实就是判断索引存在不存在。相当于 mysql 中的数据库
public void GetIndex() throws IOException{
//请求索引请求
GetIndexRequest request = new GetIndexRequest("fjj-index");
//客户端执行
IndicesClient indices = client.indices();
//判断是不是存在
boolean b = indices.exists(request,RequestOptions.DEFAULT);
System.out.println(b);
}
这是存在的结果,返回的是true
假设我们获取索引那一块写的是我们没有的索引,返回的就是
这里需要注意的是,我们的 获取索引其实就相当于Mysql 中获取一个数据库,所以只能判断存在或者不存在。
删除索引
//删除索引
@Test
public void DeleteIndex() throws IOException {
//删除索引的请求
DeleteIndexRequest request = new DeleteIndexRequest("fjj-index");
//客户端执行
IndicesClient client = this.client.indices();
//执行删除操作
AcknowledgedResponse delete = client.delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
结果
成功把我们的索引删除
文档的操作
1,在文档操作前我们需要添加下fastjson 的依赖
<!-- 添加json 的依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.66</version>
</dependency>
2,写一个pojo 类用来创建对象
添加文档
//添加文档
@Test
public void AddDocument() throws IOException {
//创建对象
User user = new User("冯娇娇", 18, "女");
//创建请求
IndexRequest indexRequest = new IndexRequest("fjj-index");
//设置请求的规则 相当于之前命令行的 put/fjj-index/_doc/1
indexRequest.id("1");
//过期时间
indexRequest.timeout("1s");
//把我们的请求放入json
indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求
IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
//查看添加的信息
System.out.println(index.toString());
//查看状态
System.out.println(index.status());
}
结果
添加成功!
获取文旦是否存在
//获取文档 判断是否存在 get/index/doc/1
@Test
public void GetDocument() throws IOException{
//获取请求
GetRequest getRequest = new GetRequest("fjj-index", "1");
//不获取返回_source 的上下文了
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
//客户端执行
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println("exists = " + exists);
}
}
结果
获取文档的具体信息
//获取文档的具体信息
@Test
public void GetDocument1() throws IOException{
GetRequest getRequest = new GetRequest("fjj-index", "1");
//客户端执行
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
//打印文档内容
System.out.println(getResponse.getSourceAsString());
//输出查看
System.out.println("getResponse = " + getResponse);
}
修改文档
//修改文档信息
@Test
public void UpdateDocument() throws IOException{
// 获取更新的信息
UpdateRequest updateRequest = new UpdateRequest("fjj-index", "1");
//设置 响应时间
updateRequest.timeout("1s");
//获取对象
User user = new User("冯娇娇", 16, "女");
//转换成Json
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
//客户端执行
UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
//打印状态
System.out.println(update.status());
}
}
结果
删除文档
//删除文档
@Test
public void DeleteDocument() throws IOException{
//获取删除的文档请求
DeleteRequest deleteRequest = new DeleteRequest("fjj-index", "1");
//设置响应时间
deleteRequest.timeout("1s");
//客户端执行
DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(delete.status());
}
以上简单的增删查改结束!!!!!!!!!!!!!!!!!!、
特殊情况 批量添加 以及 花式查询
//批量添加文档
@Test
public void BulkRequest() throws IOException{
//获取批量添加的请求
BulkRequest bulkRequest = new BulkRequest();
//设置响应时间
bulkRequest.timeout("10s");
//创建批量添加的集合
ArrayList<User> list = new ArrayList<>();
list.add(new User("f",13,"nan"));
list.add(new User("j1",13,"nan"));
list.add(new User("j2",13,"nan"));
list.add(new User("j3",13,"nan"));
//循环
for (int i = 0; i <list.size() ; i++) {
bulkRequest.add(
new IndexRequest("fjj-index")
.id(""+(i+1))
.source(JSON.toJSONString(list.get(i)),XContentType.JSON));
}
//客户端执行
BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulk.hasFailures());
}
}
结果
查询
//查询
@Test
public void testSearch() throws IOException{
//获取查询的请求
SearchRequest searchRequest = new SearchRequest("fjj-index");
//搜索的构建条件
SearchSourceBuilder builder = new SearchSourceBuilder();
//查询条件我们可以用 QueryBuilders 工具来实现
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "j1");
builder.query(termQueryBuilder);
builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(builder);
//客户端执行
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
//输出
System.out.println(JSON.toJSONString(search.getHits()));
for (SearchHit hit : search.getHits()) {
System.out.println("hit = " + hit);
}
}
}
结果