SpringBoot集成ES以及常用API演示

查看官方文档

地址:https://www.elastic.co/guide/index.html
找到Elasticsearch Clients,点进去
SpringBoot集成ES以及常用API演示_第1张图片
里面有各种语言的客户端,推荐Java REST Client,Java原生APIJava API
SpringBoot集成ES以及常用API演示_第2张图片
高级客户端是对低级客户端的封装,在Getting started中能依次看到兼容性、API文档、Maven依赖等介绍。
SpringBoot集成ES以及常用API演示_第3张图片
官方文档上写的依赖
SpringBoot集成ES以及常用API演示_第4张图片
初始化
SpringBoot集成ES以及常用API演示_第5张图片

SpringBoot项目集成ES

访问https://start.spring.io/,添加依赖时搜索elastic,会出现ES相关依赖。
SpringBoot集成ES以及常用API演示_第6张图片
生成的springboot项目中:


<dependency>
	<groupId>org.springframework.bootgroupId>
	<artifactId>spring-boot-starter-data-elasticsearchartifactId>
dependency>

如有必要,在pom.xml文件中自己定义ES版本依赖,保证和本地版本一致。
version

配置类

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

}

或者在application.yml中配置
SpringBoot集成ES以及常用API演示_第7张图片

查看ES相关源码

SpringBoot集成ES以及常用API演示_第8张图片
虽然这里导入了三个类,但都是静态内部类,核心类就一个:ElasticsearchRestClientConfigurations
SpringBoot集成ES以及常用API演示_第9张图片

package org.springframework.boot.autoconfigure.elasticsearch;

import ...
/**
 * Elasticsearch rest client infrastructure configurations.
 */
class ElasticsearchRestClientConfigurations {

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnMissingBean(RestClientBuilder.class)
	static class RestClientBuilderConfiguration {
		//RestClientBuilder
		@Bean
		RestClientBuilder elasticsearchRestClientBuilder(
				ElasticsearchRestClientProperties properties,
				ObjectProvider<RestClientBuilderCustomizer> builderCustomizers) {
			HttpHost[] hosts = properties.getUris().stream()
					.map(this::createHttpHost).toArray(HttpHost[]::new);
			RestClientBuilder builder = RestClient.builder(hosts);
			//...
			return builder;
		}
		//...
	}

	@Configuration(proxyBeanMethods = false)
	@ConditionalOnClass(RestHighLevelClient.class)
	static class RestHighLevelClientConfiguration {
		//RestHighLevelClient 高级客户端
		@Bean
		@ConditionalOnMissingBean
		RestHighLevelClient elasticsearchRestHighLevelClient(RestClientBuilder restClientBuilder) {
			return new RestHighLevelClient(restClientBuilder);
		}
		//...
	}

	@Configuration(proxyBeanMethods = false)
	static class RestClientFallbackConfiguration {
		//RestClient 普通客户端
		@Bean
		@ConditionalOnMissingBean
		RestClient elasticsearchRestClient(RestClientBuilder builder) {
			return builder.build();
		}
	}
	//...
}

具体的API测试

索引的创建、获取、删除

  • 创建索引
    @Autowired
    public RestHighLevelClient client;
    
    //测试索引的创建
    @Test
    public void testCreateIndex() throws IOException {
    	//创建索引请求
    	CreateIndexRequest request = new CreateIndexRequest("hany_index");
    	//执行创建请求
    	CreateIndexResponse response = client.indices()
    			.create(request, RequestOptions.DEFAULT);
    	System.out.println(response);
    }
    
    结果:
    SpringBoot集成ES以及常用API演示_第10张图片
  • 获取索引
    //测试获取索引,判断索引是否存在
    @Test
    public void testGetIndex() throws IOException {
    	GetIndexRequest request = new GetIndexRequest("hany_index1");
    	boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    	System.out.println(exists);
    }
    
  • 删除索引
    //测试删除索引
    @Test
    public void testDelIndex() throws IOException {
    	DeleteIndexRequest request = new DeleteIndexRequest("hany_index");
    	AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
    	System.out.println(delete.isAcknowledged());
    }
    

文档的增删改

  • 添加文档
    //测试添加文档
    @Test
    public void testAddDoc() throws IOException {
    	User user = new User("hany", 5);
    	IndexRequest request = new IndexRequest("hany_index");
    	//PUT /hany_index/_doc/1
    	request.id("1");
    	//规则  超时时间1秒,即请求时间超过1s不再请求。也可以不设置
    	request.timeout(TimeValue.timeValueSeconds(1));
    	//request.timeout("1s");//与上同效
    	//将我们的数据放入请求
    	request.source(JSON.toJSONString(user), XContentType.JSON);
    	//客户端发送请求,获取响应的结果
    	IndexResponse response = client.index(request, RequestOptions.DEFAULT);
    	System.out.println(response);//IndexResponse[index=hany_index,type=_doc,id=1,version=1,
    	//result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
    	System.out.println(response.status());//CREATED
    }
    
  • 获取文档
    //获取文档,判断文档是否存在	get /hany_index/_doc/1
    @Test
    public void testGetDoc() throws IOException {
    	GetRequest request = new GetRequest("hany_index", "1");
    	//不获取返回的"_source"上下文。仅做演示,可以不写
    	request.fetchSourceContext(new FetchSourceContext(false));
    	//排序字段。仅做演示,可以不写
    	request.storedFields("_none_");
    	boolean exists = client.exists(request, RequestOptions.DEFAULT);
    	System.out.println(exists);
    }
    
    //获得文档的信息
    @Test
    public void testGetDocInfo() throws IOException {
    	GetRequest request = new GetRequest("hany_index", "1");
    	GetResponse response = client.get(request, RequestOptions.DEFAULT);
    	System.out.println(response.getSourceAsString());
    	//{"age":5,"name":"hany"},可以看到是个map
    	System.out.println(response);//这里返回的内容和命令是一样的
    	//{"_index":"hany_index","_type":"_doc","_id":"1","_version":1,"_seq_no":0,
    	//"_primary_term":1,"found":true,"_source":{"age":5,"name":"hany"}}
    }
    
  • 更新文档
    //更新文档信息
    @Test
    public void testUpdateDoc() throws IOException {
    	UpdateRequest request = new UpdateRequest("hany_index", "1");
    	request.timeout("1s");
    	//request.timeout(TimeValue.timeValueSeconds(1000));
    	User user = new User("hanyjava", 4);
    	request.doc(JSON.toJSONString(user), XContentType.JSON);
    	UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
    	System.out.println(response.status());
    }
    
  • 删除文档
    //删除文档记录
    @Test
    public void testDeleteDoc() throws IOException {
    	DeleteRequest request = new DeleteRequest("hany_index", "1");
    	request.timeout("1s");
    	DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
    	System.out.println(response.status());//OK
    }
    
  • 批量增删改
    //真实项目会批量操作数据(增删改)
    @Test
    public void testBulkRequest() throws IOException {
    	BulkRequest request = new BulkRequest();
    	request.timeout("1s");
    	
    	ArrayList<User> list = new ArrayList<>();
    	list.add(new User("red", 12));
    	list.add(new User("blue1", 13));
    	list.add(new User("blue2", 13));
    	list.add(new User("blue3", 13));
    	list.add(new User("blue4", 13));
    	
    	for (int i=0; i<list.size(); i++) {
    		//这里演示插入数据,要更新、删除,修改里面的请求即可
    		request.add(new IndexRequest("hany_index")
    				.id(""+(i+1))
    				.source(JSON.toJSONString(list.get(i)), XContentType.JSON));
    	}
    	BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
    	System.out.println(response.hasFailures());//是否失败
    }
    

查询

/*
 * 查询
 * HighlightBuilder 高亮构建
 * TermQueryBuilder 精确查询
 * MatchAllQueryBuilder 匹配所有
 */
@Test
public void testSearch() throws IOException {
	SearchRequest request = new SearchRequest("hany_index");
	//构建搜索条件
	SearchSourceBuilder builder = new SearchSourceBuilder();
	/*
	 * 查询条件,可以使用QueryBuilders工具来实现
	 * QueryBuilders.termQuery() 精确查询
	 * QueryBuilders.matchAllQuery() 匹配所有
	 */
	TermQueryBuilder query = QueryBuilders.termQuery("name", "red");
	builder.query(query);
	builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
	request.source(builder);
	SearchResponse response = client.search(request, RequestOptions.DEFAULT);
	SearchHits hits = response.getHits();//搜索结果封装在这个SearchHits中
	System.out.println(JSON.toJSONString(hits));
	System.out.println("==========================");
	for (SearchHit hit : hits.getHits()) {
		System.out.println(hit.getSourceAsMap());//{name=red, age=12}
	}
}

你可能感兴趣的:(SpringBoot集成ES以及常用API演示)