SpringBoot_Elasticsearch
第一步
<properties>
<java.version>1.8</java.version>
<elasticsearch.version>7.15.0</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
</dependency>
</dependencies>
第二步
spring:
elasticsearch:
rest:
uris:
第三步
- 定义配置类
RestHighLevelClientConfig
@Configuration
public class RestHighLevelClientConfig {
@Value("${spring.elasticsearch.rest.uris}")
private String uris;
@Bean
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(RestClient.builder(this.createHttpHost()));
}
private HttpHost createHttpHost() {
Asserts.check(ObjectUtils.isEmpty(uris), "ElasticSearch cluster ip address cannot empty");
String url = uris.split(",")[0].trim();
return new HttpHost(url.split(":")[0], Integer.parseInt(url.split(":")[1]));
}
}
第四步
- 定义数据实体类
ElasticSearchDocument
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ElasticSearchDocument<T> {
private String id;
private T data;
}
第五步
public class BaseException extends RuntimeException {
public BaseException(String message) {
super(message);
}
public BaseException(String message, Throwable cause) {
super(message, cause);
}
}
第六步
- 定义方法接口
ElasticSearchService
@Component
public interface ElasticSearchService {
boolean createIndex(String index, Map<String, Map<String, Object>> properties) throws IOException;
boolean isExistIndex(String index) throws IOException;
boolean deleteIndex(String index) throws IOException;
void save(String index, ElasticSearchDocument<?> document) throws IOException;
void update(String index, ElasticSearchDocument<?> document) throws IOException;
<T> void saveAll(String index, List<ElasticSearchDocument<T>> documentList) throws IOException;
void delete(String index, String id) throws IOException;
void deleteByQuery(String index, QueryBuilder queryBuilder) throws IOException;
void deleteAll(String index, List<String> idList) throws IOException;
<T> T get(String index, String id, Class<T> resultType) throws IOException;
<T> List<T> searchByQuery(String index, SearchSourceBuilder sourceBuilder, Class<T> resultType) throws IOException;
Aggregations searchAgg(SearchSourceBuilder searchSourceBuilder, String... indices);
}
第七步
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {
private static final int DEFAULT_SHARDS = 3;
private static final int DEFAULT_REPLICAS = 1;
@Autowired
private RestHighLevelClient restHighLevelClient;
@Override
public boolean createIndex(String index, Map<String, Map<String, Object>> properties) throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject()
.startObject("mappings")
.field("properties", properties)
.endObject()
.startObject("settings")
.field("number_of_shards", DEFAULT_SHARDS)
.field("number_of_replicas", DEFAULT_REPLICAS)
.endObject()
.endObject();
CreateIndexRequest request = new CreateIndexRequest(index).source(builder);
CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
return response.isAcknowledged();
}
@Override
public boolean isExistIndex(String index) throws IOException {
GetIndexRequest getIndexRequest = new GetIndexRequest(index);
getIndexRequest.local(false);
getIndexRequest.humanReadable(true);
getIndexRequest.includeDefaults(false);
return restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
}
@Override
public boolean deleteIndex(String index) throws IOException {
try {
DeleteIndexRequest request = new DeleteIndexRequest(index);
AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
return response.isAcknowledged();
} catch (ElasticsearchException exception) {
if (exception.status() == RestStatus.NOT_FOUND) {
exception.printStackTrace();
throw new BaseException("Not found index: " + index);
}
throw exception;
}
}
@Override
public void save(String index, ElasticSearchDocument<?> document) throws IOException {
IndexRequest indexRequest = new IndexRequest(index);
indexRequest.id(document.getId());
indexRequest.source(JSON.toJSONString(document.getData()), XContentType.JSON);
restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
}
@Override
public void update(String index, ElasticSearchDocument<?> document) throws IOException {
UpdateRequest updateRequest = new UpdateRequest(index, document.getId());
updateRequest.doc(JSON.toJSONString(document.getData()), XContentType.JSON);
restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
}
@Override
public <T> void saveAll(String index, List<ElasticSearchDocument<T>> documentList) throws IOException {
if (ObjectUtils.isEmpty(documentList)) {
return;
}
BulkRequest bulkRequest = new BulkRequest();
documentList.forEach(doc -> {
bulkRequest.add(new IndexRequest(index)
.id(doc.getId())
.source(JSON.toJSONString(doc.getData()), XContentType.JSON));
});
restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
}
public void delete(String index, String id) throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(index, id);
restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
}
public void deleteByQuery(String index, QueryBuilder queryBuilder) throws IOException {
DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest(index).setQuery(queryBuilder);
deleteRequest.setConflicts("proceed");
restHighLevelClient.deleteByQuery(deleteRequest, RequestOptions.DEFAULT);
}
public void deleteAll(String index, List<String> idList) throws IOException {
if (ObjectUtils.isEmpty(idList)) {
return;
}
BulkRequest bulkRequest = new BulkRequest();
idList.forEach(id -> bulkRequest.add(new DeleteRequest(index, id)));
restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
}
public <T> T get(String index, String id, Class<T> resultType) throws IOException {
GetRequest getRequest = new GetRequest(index, id);
GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
String resultAsString = response.getSourceAsString();
return JSON.parseObject(resultAsString, resultType);
}
public <T> List<T> searchByQuery(String index, SearchSourceBuilder sourceBuilder, Class<T> resultType) throws IOException {
SearchRequest searchRequest = new SearchRequest(index).source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = response.getHits().getHits();
List<T> results = new ArrayList<>(hits.length);
for (SearchHit hit : hits) {
String sourceAsString = hit.getSourceAsString();
results.add(JSON.parseObject(sourceAsString, resultType));
}
return results;
}
public Aggregations searchAgg(SearchSourceBuilder searchSourceBuilder, String... indices) {
try {
SearchRequest searchRequest = new SearchRequest(indices).source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
return searchResponse.getAggregations();
} catch (IOException e) {
e.printStackTrace();
throw new BaseException("ElasticSearch client exception");
}
}
}