目录
Elasticsearch是一个开源的分布式搜索和分析引擎,它构建在Apache Lucene库之上。它提供了一个强大而灵活的全文搜索引擎,可以应用于各种应用场景,包括实时数据分析、日志分析、企业搜索等。
以下是Elasticsearch的主要特点和功能:
-
分布式架构:Elasticsearch使用分布式架构,可以在多个节点上存储和处理数据,实现高可用性和可伸缩性。
-
实时数据索引和搜索:Elasticsearch能够实时地将数据索引和搜索,可以快速地处理大量的数据。
-
多种查询方式:Elasticsearch支持全文搜索、精确匹配、模糊搜索、聚合查询等不同的查询方式,可以根据需求进行灵活的查询操作。
-
多语言支持:Elasticsearch支持多种语言的全文搜索和分析,适用于不同地区和不同语言的应用。
-
分布式数据处理:Elasticsearch提供了丰富的API,可以进行复杂的数据处理和分析,如聚合、过滤、排序等。
-
数据复制与故障恢复:Elasticsearch使用数据复制机制,将数据分布到多个节点,以提供数据冗余和故障恢复的能力。
-
插件生态系统:Elasticsearch拥有丰富的插件生态系统,可以扩展其功能,满足各种特定需求。
Elasticsearch是一个功能强大且广泛应用的搜索和分析引擎,适用于各种类型的应用场景。它提供了简单易用的API和丰富的功能,使得处理大规模数据和实时搜索变得更加高效和便捷。
框架:springboot+gradle
一、引入依赖
在build.gradle
文件中添加Elasticsearch Java的依赖。这是连接Elasticsearch并使用其功能所必需的步骤。
implementation("org.elasticsearch:elasticsearch:7.6.1") implementation("org.elasticsearch.client:elasticsearch-rest-high-level-client:7.6.1")
二、配置application
将Elasticsearch连接信息(如主机和端口)配置到应用程序中,以便能够连接到Elasticsearch服务器。
elasticsearch:
username: elastic
password: elastic
uris: localhost:9200
三、 配置文件
创建一个配置类,用于在应用程序中注入Elasticsearch连接信息,使其能够正常运行。
@Configuration
@RequiredArgsConstructor
public class ElasticsearchConfig{
public static ObjectMapper objectMapper = new ObjectMapper();
@Bean("restHighLevelClient")
public RestHighLevelClient elasticsearchClient(ElasticsearchProperties elasticsearchProperties){
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticsearchProperties.getUsername(), elasticsearchProperties.getPassword()));
RestClientBuilder restClientBuilder = RestClient.builder(HttpHost.create(elasticsearchProperties.getUris().get(0)))
.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
return new RestHighLevelClient(restClientBuilder);
}
}
四、业务代码
业务代码:包括创建、获取和删除索引,以及添加、删除和批量操作文档数据;还包括根据单个条件删除符合条件的文档数据。这些是实际处理Elasticsearch索引和数据的核心功能。
Controller中注入RestHighLevelClient、EsIndexService
private final RestHighLevelClient restHighLevelClient;
private final EsIndexService esIndexService;
1.创建索引
@ApiOperation("创建索引")
@PostMapping("/add")
public ApiResponse<Boolean> save(@ApiParam("索引名称") @RequestParam("es_name") String esName) throws IOException {
CreateIndexRequest createIndexRequest = new CreateIndexRequest(esName);
CreateIndexResponse indexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = indexResponse.isAcknowledged();
if (acknowledged) {
return ApiResponse.success(acknowledged);
} else {
return ApiResponse.failure("创建索引失败", acknowledged);
}
}
2.获取索引
@ApiOperation("获取索引")
@GetMapping("/list")
public ApiResponse<Map<String, Set<AliasMetaData>>> list() throws IOException {
GetAliasesRequest request = new GetAliasesRequest();
GetAliasesResponse getAliasesResponse = restHighLevelClient.indices().getAlias(request, RequestOptions.DEFAULT);
return ApiResponse.success(getAliasesResponse.getAliases());
}
3.删除索引
@ApiOperation("删除索引")
@PostMapping("/delete")
public ApiResponse<Boolean> delete(@ApiParam("索引名称") @RequestParam("es_name") String esName) throws IOException {
SearchRequest request = new SearchRequest();
request.indices(esName);
SearchSourceBuilder query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
request.source(query);
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
long total = hits.getTotalHits().value;
if (total > 0L) {
return ApiResponse.failure("索引下包含" + total + "条数据,咱不能删除", false);
}
DeleteIndexRequest getIndexRequest = new DeleteIndexRequest(esName);
AcknowledgedResponse delete = restHighLevelClient.indices().delete(getIndexRequest, RequestOptions.DEFAULT);
boolean acknowledged = delete.isAcknowledged();
if (acknowledged) {
return ApiResponse.success(acknowledged);
} else {
return ApiResponse.failure("删除索引失败", acknowledged);
}
}
4.删除数据
@ApiOperation("删除数据")
@PostMapping("/deleteById")
public ApiResponse<Boolean> deleteById(
@ApiParam("索引名称") @RequestParam("es_name") String esName,
@ApiParam("主键") @RequestParam("id") Integer id) throws IOException {
boolean flag = esIndexService.delete(esName, id);
if (flag) {
return ApiResponse.success(flag);
} else {
return ApiResponse.failure("删除失败", flag);
}
}
service代码如下
@Override
public Boolean delete(String indexName, Integer id) throws IOException {
DeleteRequest request = new DeleteRequest();
request.index(indexName).id(String.valueOf(id));
restHighLevelClient.delete(request, RequestOptions.DEFAULT);
return true;
}
5.新增数据
@ApiOperation("新增数据")
@PostMapping("/saveData")
public ApiResponse<Boolean> saveData(@ApiParam("json格式数据") @RequestParam("data") String data,
@ApiParam("主键") @RequestParam("id") Integer id,
@ApiParam("索引名称") @RequestParam("es_name") String esName) throws IOException {
boolean flag = esIndexService.save(data, id, esName);
if (flag) {
return ApiResponse.success(flag);
} else {
return ApiResponse.failure("新建数据", flag);
}
}
service代码如下
@Override
public Boolean save(String data, Integer id, String indexName) throws IOException {
IndexRequest indexRequest = new IndexRequest();
indexRequest.index(indexName);
indexRequest.id(String.valueOf(id));
indexRequest.source(data, XContentType.JSON);
// 插入数据
restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
return true;
}
6.批量删除数据
@ApiOperation("批量新增数据")
@PostMapping("/saveBatchData")
public ApiResponse<Boolean> saveData(@ApiParam("json格式数据") @RequestParam("data") List<String> data,
@ApiParam("索引名称") @RequestParam("es_name") String esName) throws IOException {
boolean flag = esIndexService.saveBatch(data, esName);
if (flag) {
return ApiResponse.success(flag);
} else {
return ApiResponse.failure("批量新建数据", flag);
}
}
service代码如下
@Override
public Boolean saveBatch(List<String> dataList, String indexName) throws IOException {
if (CollectionUtils.isEmpty(dataList)) {
return flag;
}
BulkRequest bulkRequest = new BulkRequest();
dataList.stream().forEach(
data -> {
IndexRequest indexRequest = new IndexRequest().index(indexName).source(data, XContentType.JSON);
bulkRequest.add(indexRequest);
}
);
restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return true;
}
7.批量新增数据
@ApiOperation("批量删除数据")
@PostMapping("/deleteBatch")
public ApiResponse<Boolean> deleteBatch(@ApiParam("id") @RequestParam("data") List<Integer> data,
@ApiParam("索引名称") @RequestParam("es_name") String esName) throws IOException {
boolean flag = esIndexService.deleteBatch(data, esName);
if (flag) {
return ApiResponse.success(flag);
} else {
return ApiResponse.failure("批量删除数据", flag);
}
}
service代码如下
@Override
public Boolean deleteBatch(List<Integer> dataList, String indexName) throws IOException {
BulkRequest bulkRequest = new BulkRequest();
dataList.stream().forEach(
id -> {
DeleteRequest indexRequest = new DeleteRequest().index(indexName).id(String.valueOf(id));
bulkRequest.add(indexRequest);
}
);
restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return true;
}
8.根据单个条件删除
/**
* 根据条件删除
* @param indexName 索引名称
* @param FieldName 字段名称
* @param FieldValue 字段值
* @return
* @throws IOException
*/
@Override
public Boolean deleteByField(String indexName, String FieldName, String FieldValue) throws IOException {
boolean flag = true;
DeleteByQueryRequest request = new DeleteByQueryRequest(indexName);
request.setQuery(new TermQueryBuilder(FieldName, FieldValue));
BulkByScrollResponse response = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
if (ZERO > response.getStatus().getDeleted()) {
flag = false;
}
return flag;
}
五、总结
在使用Java应用程序连接Elasticsearch并进行索引管理和数据操作时,需要完成以下步骤:
首先,需要在xml或gradle文件中引入Elasticsearch的依赖。其次,需要在应用程序中配置Elasticsearch连接信息(如主机和端口)。
然后,创建一个配置类,用于将Elasticsearch连接信息注入到应用程序中,以便能够正常连接到Elasticsearch服务器。
最后,在业务代码中,可以通过API创建、获取和删除索引,以及添加、删除和批量操作文档数据。同时,也可以根据单个条件删除符合条件的文档数据。