SpringBoot integrates ElasticSearch (different dependencies, business code and JPA methods are also different)

Framework: springboot + gradle

1. Introduce dependencies

implementation("org.elasticsearch:elasticsearch:7.6.1")
implementation("org.elasticsearch.client:elasticsearch-rest-high-level-client:7.6.1")

2. Configure application

elasticsearch:
    username: elastic
    password: elastic
    uris: localhost:9200

3. Configuration file

@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);
    }
}

4. Business code

Inject RestHighLevelClient and EsIndexService into Controller

private final RestHighLevelClient restHighLevelClient;

private final EsIndexService esIndexService;

1. Create index

 @ApiOperation("Create index")
    @PostMapping("/add")
    public ApiResponse<Boolean> save(@ApiParam("index name") @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("Failed to create index", acknowledged);
        }
    }

2. Get index

 @ApiOperation("Get index")
    @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. Delete index

 @ApiOperation("Delete index")
    @PostMapping("/delete")
    public ApiResponse<Boolean> delete(@ApiParam("index name") @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("The index contains" + total + "data, we cannot delete", 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("Failed to delete index", acknowledged);
        }
    }

4. Delete data

    @ApiOperation("Delete data")
    @PostMapping("/deleteById")
    public ApiResponse<Boolean> deleteById(
                                           @ApiParam("index name") @RequestParam("es_name") String esName,
                                           @ApiParam("primary key") @RequestParam("id") Integer id) throws IOException {
        boolean flag = esIndexService.delete(esName, id);
        if (flag) {
            return ApiResponse.success(flag);
        } else {
            return ApiResponse.failure("Deletion failed", flag);
        }
    }

The service code is as follows

 @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. Add new data

 @ApiOperation("New data")
    @PostMapping("/saveData")
    public ApiResponse<Boolean> saveData(@ApiParam("json format data") @RequestParam("data") String data,
                                         @ApiParam("primary key") @RequestParam("id") Integer id,
                                         @ApiParam("index name") @RequestParam("es_name") String esName) throws IOException {
        boolean flag = esIndexService.save(data, id, esName);
        if (flag) {
            return ApiResponse.success(flag);
        } else {
            return ApiResponse.failure("New data", flag);
        }
    }

The service code is as follows

 @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);
        //Insert data
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        return true;
    }

6. Delete data in batches

 @ApiOperation("Batch new data")
    @PostMapping("/saveBatchData")
    public ApiResponse<Boolean> saveData(@ApiParam("json format data") @RequestParam("data") List<String> data,
                                         @ApiParam("index name") @RequestParam("es_name") String esName) throws IOException {
        boolean flag = esIndexService.saveBatch(data, esName);
        if (flag) {
            return ApiResponse.success(flag);
        } else {
            return ApiResponse.failure("Batch new data", flag);
        }
    }

The service code is as follows

 @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. Add data in batches

 @ApiOperation("Delete data in batches")
    @PostMapping("/deleteBatch")
    public ApiResponse<Boolean> deleteBatch(@ApiParam("id") @RequestParam("data") List<Integer> data,
                                            @ApiParam("index name") @RequestParam("es_name") String esName) throws IOException {
        boolean flag = esIndexService.deleteBatch(data, esName);
        if (flag) {
            return ApiResponse.success(flag);
        } else {
            return ApiResponse.failure("Delete data in batches", flag);
        }
    }

The service code is as follows

 @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. Delete based on a single condition

/**
     * Delete based on conditions
     * @param indexName index name
     * @param FieldName field name
     * @param FieldValue field value
     * @return
     * @throwsIOException
     */
    @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;
    }