1.方式一
1.1 依赖
【不使用 spring-boot-starter-data-elasticsearch 就可以脱离 springboot 版本的限制,可以自行选择ES的版本】我用的是 springboot 2.2.5.RELEASE 版本,ES部署文件为 elasticsearch-6.4.3.tar.gz,这里只贴出主要依赖:
<!-- ElasticSearch Server -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.4.3</version>
</dependency>
<!-- Java High Level REST Client -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.4.3</version>
</dependency>
1.2 配置信息
这里根据elasticsearch服务端的地址进行配置:
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")
));
return client;
}
}
1.3 客户端使用
@SpringBootTest
class EsApiApplicationTests {
@Autowired
@Qualifier(value = "restHighLevelClient")
private RestHighLevelClient client;
/*1.创建索引*/
@Test
void createIndex() throws IOException {
// 创建请求
CreateIndexRequest request = new CreateIndexRequest("yz_index");
// 执行请求,获取响应
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println("creatIndex--" + response);
}
/*2.获取索引,判断是否存在*/
@Test
void getIndex() throws IOException {
// 创建请求
GetIndexRequest request = new GetIndexRequest("yz_index");
// 执行请求,获取响应
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println("getIndex--exists--" + exists);
}
/*3.删除索引*/
@Test
void deleteIndex() throws IOException {
// 创建请求
DeleteIndexRequest request = new DeleteIndexRequest("yz_index");
// 执行请求
AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println("deleteIndex--" + response);
}
/*4.添加文档*/
@Test
void addDocument() throws IOException {
// 创建对象
User user = new User("Java虚拟机", 30);
// 创建索引,即获取索引
IndexRequest indexRequest = new IndexRequest("yz_index");
// 添加规则 /index/_doc/id
indexRequest.id("1");
indexRequest.timeout(TimeValue.timeValueSeconds(1));
// 存入对象
indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
// 发送请求
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println("addDocument--" + response);
}
/*5.获取文档是否存在*/
@Test
void getDocument() throws IOException {
// 创建get请求
GetRequest getRequest = new GetRequest("yz_index", "1");
// 不获取返回的_source的上下文
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
// 发送请求
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println("addDocument--" + exists);
/*6.获取文档信息*/
if (exists) {
// 创建请求
GetRequest getRequest1 = new GetRequest("yz_index", "1");
// 发送请求
GetResponse response = client.get(getRequest1, RequestOptions.DEFAULT);
System.out.println("source--" + response.getSource());
System.out.println("getDocument--" + response.getSourceAsString());
}
/*7.更新文档信息*/
if (exists) {
// 创建请求
UpdateRequest updateRequest = new UpdateRequest("yz_index", "1");
updateRequest.timeout("1s");
// 修改内容
User user = new User("小米", 10);
updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println("updateDocument--" + response.status());
}
/*8.删除文档信息*/
if (exists) {
// 创建请求
DeleteRequest deleteRequest = new DeleteRequest("yz_index", "1");
deleteRequest.timeout("1s");
// 修改内容
DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println("deleteDocument--" + response.status());
}
}
/*9.批量添加文档*/
@Test
void batchAddDocument() throws IOException {
// 批量请求
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
// 创建对象
ArrayList<User> userArrayList = new ArrayList<>();
userArrayList.add(new User("小米1", 1));
userArrayList.add(new User("小米2", 2));
userArrayList.add(new User("小米3", 3));
userArrayList.add(new User("小米4", 4));
userArrayList.add(new User("小米5", 5));
// 添加请求
for (int i = 0; i < userArrayList.size(); i++) {
bulkRequest.add(new IndexRequest("yz_index")
.id("" + (i + 2))
.source(JSON.toJSONString(userArrayList.get(i)), XContentType.JSON));
}
// 执行请求
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println("batchAddDocument--" + response.status());
}
/*10.查询*/
@Test
void search() throws IOException {
// 创建请求
SearchRequest searchRequest = new SearchRequest("jd_index");
// 构建搜索条件
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "杜伽");// 精确查询
searchSourceBuilder.query(termQueryBuilder);
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(searchSourceBuilder);
// 执行请求
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
// 解析查询结果
System.out.println("search--getHists--" + JSON.toJSONString(response.getHits()));
for (SearchHit documentFields : response.getHits()) {
System.out.println("search--getHist--" + documentFields.getSourceAsMap());
}
}
}
2.方式二
2.1 依赖
我用的是 springboot 2.5.4【所以spring-boot-starter-data-elasticsearch 的版本也是 2.5.4】此时对应的 elasticsearch 服务端和客户端的版本是 7.12.1 那要部署的ES版本也要是 7.12.1:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.2 配置信息
spring:
elasticsearch:
rest:
uris: localhost:9200
2.3 客户端使用
@SpringBootTest
class EsStarterApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
void contextLoads() {
// 由于不同版本的API不同【没有参考价值】,这里不再贴出测试代码。
}
}
3.注意事项
不同的 elasticsearch 版本有不同的 API 这就给升级造成了阻碍,为了避免这种情况,我们可以使用elasticsearch的 HTTP 客户端 Jest,下篇文章会详细说明。