ElasticSearch集成SpringBoot

找官方文档!

ElasticSearch集成SpringBoot_java

  1. 找到原生的依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
  1. 找对象
  2. 分析这个类中的方法即可!

配置基本的项目

问题:一定要保证 我们的导入的依赖和我们的 es 版本一致

ElasticSearch集成SpringBoot_java_02

ElasticSearch集成SpringBoot_elasticsearch_03

源码中提供对象!

ElasticSearch集成SpringBoot_elasticsearch_04

虽然这里导入3个类,静态内部类,核心类就一个!

/**
* Elasticsearch rest client infrastructure configurations.
*
* @author Brian Clozel
* @author Stephane Nicoll
*/
class RestClientConfigurations {
@Configuration(proxyBeanMethods = false)
static class RestClientBuilderConfiguration {
// RestClientBuilder
@Bean
@ConditionalOnMissingBean
RestClientBuilder elasticsearchRestClientBuilder(RestClientProperties
properties,
ObjectProvider<RestClientBuilderCustomizer> builderCustomizers) {
HttpHost[] hosts =
properties.getUris().stream().map(HttpHost::create).toArray(HttpHost[]::new);
RestClientBuilder builder = RestClient.builder(hosts);
PropertyMapper map = PropertyMapper.get();
map.from(properties::getUsername).whenHasText().to((username) -> {
CredentialsProvider credentialsProvider = new
BasicCredentialsProvider();
Credentials credentials = new
UsernamePasswordCredentials(properties.getUsername(),
properties.getPassword());
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
builder.setHttpClientConfigCallback(
(httpClientBuilder) ->
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
});
builder.setRequestConfigCallback((requestConfigBuilder) -> {

map.from(properties::getConnectionTimeout).whenNonNull().asInt(Duration::toMill
is)
.to(requestConfigBuilder::setConnectTimeout);

map.from(properties::getReadTimeout).whenNonNull().asInt(Duration::toMillis)
.to(requestConfigBuilder::setSocketTimeout);
return requestConfigBuilder;
});
builderCustomizers.orderedStream().forEach((customizer) ->
customizer.customize(builder));
return builder;
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(RestHighLevelClient.class)
static class RestHighLevelClientConfiguration {
// RestHighLevelClient 高级客户端,也是我们这里要讲,后面项目会用到的客户端
@Bean
@ConditionalOnMissingBean
RestHighLevelClient elasticsearchRestHighLevelClient(RestClientBuilder
restClientBuilder) {
return new RestHighLevelClient(restClientBuilder);
}
@Bean
@ConditionalOnMissingBean
RestClient elasticsearchRestClient(RestClientBuilder builder,
ObjectProvider<RestHighLevelClient> restHighLevelClient) {
RestHighLevelClient client = restHighLevelClient.getIfUnique();
if (client != null) {
return client.getLowLevelClient();
}
return builder.build();
}
}
@Configuration(proxyBeanMethods = false)
static class RestClientFallbackConfiguration {
// RestClient 普通的客户端!
@Bean
@ConditionalOnMissingBean
RestClient elasticsearchRestClient(RestClientBuilder builder) {
return builder.build();
}
}
}

具体的Api测试!

  1. 创建索引
  2. 判断索引是否存在
  3. 删除索引
  4. 创建文档
  5. crud文档!

配置类

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

测试类

@SpringBootTest
class ElasticsearchApplicationTests {

// 面向对象来操作
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
// 测试索引的创建 Request PUT latte_index
@Test
void contextLoads() throws IOException{
// 1、创建索引请求
CreateIndexRequest request = new CreateIndexRequest("latte_index");
// 2、客户端执行请求 IndicesClient,请求后获得响应
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);

System.out.println(createIndexResponse);
}

// 测试获取索引,判断其是否存在
@Test
void testExistIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest("latte_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);

System.out.println(exists);

}

// 测试删除索引
@Test
void testDeleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("latte_index");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);

System.out.println(delete.isAcknowledged());
}

// 测试添加文档
@Test
void testAddDocument() throws IOException {
// 创建对象
User user = new User("latte", 10);
// 创建请求
IndexRequest request = new IndexRequest("latte_index");
// 规则 put /latte_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueDays(1));
request.timeout("1s");
// 将我们的数据放入请求 json
request.source(JSON.toJSONString(user), XContentType.JSON);
// 客户端发送请求 , 获取响应的结果
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

System.out.println(indexResponse.toString());
System.out.println(indexResponse.status());// 对应我们命令返回的状态CREATED

}

// 获取文档,判断是否存在 get /index/doc/1
@Test
void testIsExists() throws IOException {
GetRequest request = new GetRequest("latte_index", "1");
// 不获取返回的 _source 的上下文了
request.fetchSourceContext(new FetchSourceContext(false));
request.storedFields("_none_");

boolean exists=client.exists(request,RequestOptions.DEFAULT);
System.out.println(exists);
}

// 获得文档的信息
@Test
void testGetDocument() throws IOException {
GetRequest getrequest = new GetRequest("latte_index", "1");
GetResponse getResponse = client.get(getrequest, RequestOptions.DEFAULT);

System.out.println(getResponse.getSourceAsString());// 打印文档的内容

System.out.println(getResponse);// 返回的全部内容和命令式一样的
}

// 更新文档的信息
@Test
void testUpdateRequest() throws IOException{
UpdateRequest updateRequest = new UpdateRequest("latte_index", "1");
updateRequest.timeout("1s");
User user = new User("latte2", 20);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}


// 删除文档记录
@Test
void testDeleteRequest() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("latte_index", "1");
deleteRequest.timeout("1s");
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}

// 特殊的,真的项目一般都会批量插入数据!
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
userList.add(new User("latte",3));
userList.add(new User("latte2",3));
userList.add(new User("latte3",3));
userList.add(new User("latte1",3));
userList.add(new User("latte1",3));
userList.add(new User("latte1",3));

for (int i = 0; i <userList.size() ; i++) {
// 批量更新和批量删除,就在这里修改对应的请求就可以了
bulkRequest.add(new IndexRequest("latte_index").id("" + (i + 1)).source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
}
BulkResponse bulkResponse = client.bulk(bulkRequest,
RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures()); // 是否失败,返回 false 代表成功!
}

// 查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 构建高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!

@Test
void testSearch() throws IOException {
SearchRequest searchRequest = new SearchRequest("latte_index");
// 构建搜索条件

SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
// 查询条件,我们可以使用 QueryBuilders 工具来实现
// QueryBuilders.termQuery 精确
// QueryBuilders.matchAllQuery() 匹配所有
sourceBuilder.highlighter();
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "latte");
// 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());
}
}
}

ElasticSearch集成SpringBoot_大数据_05