我是靠谱客的博主 忧心板栗,最近开发中收集的这篇文章主要介绍ElasticSearch入门(3)——Spring实践ElasticSearch入门(3)——Spring实践,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

ElasticSearch入门(3)——Spring实践

简单的入门之后就是实践

基于SpringBoot

<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.6.2</elasticsearch.version>
</properties>
<dependencies>
<!--<dependency>-->
<!--<groupId>org.elasticsearch.client</groupId>-->
<!--<artifactId>transport</artifactId>-->
<!--<version>7.6.2</version>-->
<!--</dependency>-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
<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>
</dependencies>

ElasticSearch版本要指定

ElasticSearch配置类

@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client ;
}
}

单元测试

实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author gyh
* @csdn https://blog.csdn.net/qq_40788718
* @date 2020/8/4 16:46
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name ;
private Integer age ;
}

测试类


import com.alibaba.fastjson.JSON;
import com.gyh.esapi.entity.User;
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.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.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.util.*;
@SpringBootTest
class EsApiApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient ;
//增加
/**
* 创建索引
* @throws IOException
*/
@Test
void testCreateOneIndex() throws IOException {
//创建索引
CreateIndexRequest request = new CreateIndexRequest("kuang_index") ;
//执行创建索引请求
CreateIndexResponse response = restHighLevelClient.indices().create(request , RequestOptions.DEFAULT) ;
System.out.println(response.index());
}
/**
* 单个插入
*/
@Test
void testCreateOneSource() throws IOException {
User user = new User("狂神说Java" , 2) ;
IndexRequest request = new IndexRequest("kuang_index") ;
request.id("2") ;
request.timeout(TimeValue.timeValueSeconds(1)) ;
request.timeout("1s") ;
request.source(JSON.toJSONString(user) , XContentType.JSON) ;
IndexResponse response = restHighLevelClient.index(request , RequestOptions.DEFAULT) ;
System.out.println(response.status()); //CREATED
}
/**
* 批量插入
*/
@Test
void testCreateBulkSource() throws IOException {
BulkRequest request = new BulkRequest("kuang_index") ;
request.timeout("10s") ;
for (int i=10 ; i<30 ; i++){
User user = new User(UUID.randomUUID().toString().substring(0, 5), (int) (Math.random() * 100)) ;
IndexRequest indexRequest = new IndexRequest("kuang_index");
indexRequest.id(""+i) ;
indexRequest.source(JSON.toJSONString(user) , XContentType.JSON) ;
request.add(indexRequest) ;
}
BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.status());
System.out.println(response.hasFailures());
System.out.println(response.toString());
//OK
//false
//org.elasticsearch.action.bulk.BulkResponse@718f805a
}
//删除
/**
* 删除单个文档
* @throws IOException
*/
@Test
void testDeleteOneSource() throws IOException {
DeleteRequest request = new DeleteRequest("kuang_index" , "1") ;
request.timeout("1s");
DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(response.status());
System.out.println(response.toString());
//OK
//DeleteResponse[index=kuang_index,type=_doc,
//id=1,version=4,result=deleted,
//shards=ShardInfo{total=2, successful=1, failures=[]}]
}
void testDeleteBulkSource(){
//和批量插入相同
}
//修改
/**
* 更新文档
* @throws IOException
*/
@Test
void testUpdateOneSource() throws IOException {
UpdateRequest request = new UpdateRequest("kuang_index" , "1") ;
User user = new User("gyh说Java" ,10) ;
request.timeout("1s") ;
request.doc(JSON.toJSONString(user) , XContentType.JSON) ;
UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(update.status());
System.out.println(update.toString());
//OK
//UpdateResponse[index=kuang_index,type=_doc,id=1,version=2,seqNo=1,
//primaryTerm=1,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]
}
/**
* 批量更新
*/
@Test
void testUpdateBulkSource() throws IOException {
//和批量插入相同
BulkRequest request = new BulkRequest("kuang_index") ;
request.timeout("10s") ;
for (int i=20 ; i<30 ; i++){
//或者根据json更新
request.add(new UpdateRequest("kuang_index" , ""+i).doc("age" , 10)) ;
}
BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(response.status());
System.out.println(response.hasFailures());
System.out.println(response.toString());
//OK
//false
//org.elasticsearch.action.bulk.BulkResponse@17b016ac
}
//查询
/**
* 条件查询
*/
@Test
void testSearch() throws IOException {
SearchRequest request = new SearchRequest("kuang_index");
SearchSourceBuilder builder = new SearchSourceBuilder();
TermQueryBuilder query = QueryBuilders.termQuery("name", "");
//
QueryBuilders.matchQuery() ; =
//
QueryBuilders.matchQuery() ;
//
QueryBuilders.termQuery() ;
//
QueryBuilders.boolQuery() ;
//
QueryBuilders.boolQuery().should() ;
//
QueryBuilders.matchAllQuery() ;
builder.query(query) ;
//
builder.from() ;
//
builder.size() ;
//
builder.profile() ;
//
builder.postFilter() ;
builder.timeout(new TimeValue(60 , TimeUnit.SECONDS)) ;
request.source(builder) ;
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
System.out.println(response.status());
System.out.println(JSON.toJSONString(response.getHits()));
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsMap());
}
}
/**
* 获取单个doc
* @throws IOException
*/
@Test
void testSelectOneSource() throws IOException {
boolean flag = isExist("kuang_index" , "1") ;
GetRequest request = new GetRequest("kuang_index" , "1") ;
GetResponse response = restHighLevelClient.get(request , RequestOptions.DEFAULT) ;
System.out.println(response.getVersion());
System.out.println(response.getSource().toString());
//1
//{name=狂神说Java, age=3}
}
/**
* 判断是否存在
* @param id
* @return
*/
boolean isExist(String index , String id) throws IOException {
GetRequest request = new GetRequest(index , id) ;
//不获取_source的上下文
request.fetchSourceContext(new FetchSourceContext(false)) ;
request.storedFields("_none_") ;
boolean flag = restHighLevelClient.exists(request , RequestOptions.DEFAULT) ;
return flag ;
}
}

最后

以上就是忧心板栗为你收集整理的ElasticSearch入门(3)——Spring实践ElasticSearch入门(3)——Spring实践的全部内容,希望文章能够帮你解决ElasticSearch入门(3)——Spring实践ElasticSearch入门(3)——Spring实践所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部