注意:我的版本是elasticsearch7.6.2、spring-boot-starter-data-elasticsearch-2.5.6
引入依赖
org.springframework.boot spring-boot-starter-data-elasticsearch
package com.mar.elasticsearchUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.index.AliasAction;
import org.springframework.data.elasticsearch.core.index.AliasActionParameters;
import org.springframework.data.elasticsearch.core.index.AliasActions;
import org.springframework.data.elasticsearch.core.index.AliasData;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.*;
@Component
@Slf4j
public class EsUtil {
private static ElasticsearchRestTemplate elasticsearchRestTemplate;
@Autowired
public EsUtil(ElasticsearchRestTemplate elasticsearchRestTemplate) {
EsUtil.elasticsearchRestTemplate = elasticsearchRestTemplate;
}
public static boolean createIndex(Class destinationClass, String indexName, String... withAliases) {
if (ObjectUtil.isNull(destinationClass)) throw new RuntimeException("参数类不能为空");
if (StrUtil.isEmpty(indexName)) throw new RuntimeException("参数名不能为空");
if (withAliases == null || withAliases.length <= 0) throw new RuntimeException("索引别名至少有一个");
for (String withAlias : withAliases) {
if (!withAlias.endsWith("_search")) {
throw new RuntimeException("索引别名只能以‘_search’结尾");
}
}
return createIndex(destinationClass, indexName, 3, 2, Integer.MAX_VALUE, withAliases);
}
public static boolean createIndex(Class destinationClass, String indexName, Integer shards, Integer replicas, Integer maxResult, String... withAliases) {
if (ObjectUtil.isNull(destinationClass)) throw new RuntimeException("参数类不能为空");
if (StrUtil.isEmpty(indexName)) throw new RuntimeException("参数名不能为空");
if (withAliases == null || withAliases.length <= 0) throw new RuntimeException("索引别名至少有一个");
for (String withAlias : withAliases) {
if (!withAlias.endsWith("_search")) {
throw new RuntimeException("索引别名只能以‘_search’结尾");
}
}
IndexCoordinates of = IndexCoordinates.of(indexName);
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(of);
boolean exists = indexOperations.exists();
if (exists) {
indexOperations.delete();
}
Map settings = new HashMap<>();
settings.put("index.number_of_shards", shards > 0 ? shards : 3);
settings.put("index.number_of_replicas", replicas > 0 ? replicas : 2);
settings.put("index.max_result_window", maxResult > 0 ? maxResult : Integer.MAX_VALUE);
Document mapping = indexOperations.createMapping(destinationClass);
indexOperations.create(settings, mapping);
AliasAction.Add add = new AliasAction.Add(AliasActionParameters.builder()
.withIndices(indexName).withAliases(withAliases).build());
return indexOperations.alias(new AliasActions(add));
}
public static boolean deleteIndexByName(String indexName) {
return elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName)).delete();
}
public static boolean isExists(String indexName) {
IndexCoordinates of = IndexCoordinates.of(indexName);
return elasticsearchRestTemplate.indexOps(of).exists();
}
public static Set getAlias(String index) {
if (StrUtil.isEmpty(index)) throw new RuntimeException("索引名不能为空");
Map> aliasesForIndex = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(index)).getAliasesForIndex();
Set set = new HashSet<>();
aliasesForIndex.forEach((key, value) -> {
value.forEach(data -> set.add(data.getAlias()));
});
return set;
}
public static boolean addAlias(String index, String... alias) {
Preconditions.checkNotNull(index);
Preconditions.checkNotNull(alias);
final IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(index));
AliasActions aliasActions = new AliasActions(new AliasAction.Add(
AliasActionParameters.builder().withIndices(index).withAliases(alias).build()
));
return indexOps.alias(aliasActions);
}
public static boolean delAlias(String index, String... alias) {
Preconditions.checkNotNull(index);
Preconditions.checkNotNull(alias);
final IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(index));
AliasActions aliasActions = new AliasActions(new AliasAction.Remove(
AliasActionParameters.builder().withIndices(index).withAliases(alias).build()
));
return indexOps.alias(aliasActions);
}
public static boolean replaceAlias(String index, String oldAlias, String newAlias) {
Preconditions.checkNotNull(index);
Preconditions.checkNotNull(oldAlias);
Preconditions.checkNotNull(newAlias);
final IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(index));
final AliasAction.Add add = new AliasAction.Add(AliasActionParameters.builder().withIndices(index).withAliases(newAlias).build());
final AliasAction.Remove remove = new AliasAction.Remove(AliasActionParameters.builder().withIndices(index).withAliases(oldAlias).build());
AliasActions aliasActions = new AliasActions(add, remove);
return indexOps.alias(aliasActions);
}
public static void saveByEntity(T t, String indexName) {
//这里的操作就是指定文档id
String id = getFieldId(t);
IndexQuery build = new IndexQueryBuilder()
.withId(id)
.withObject(t).build();
elasticsearchRestTemplate.index(build, IndexCoordinates.of(indexName));
}
public static void saveBatchByEntities(Map> map) {
if (map != null && map.size() > 0)
map.forEach((key, value) -> saveBatchByEntities(value, key));
}
public static void saveBatchByEntities(List sourceList, String indexName) {
List queryList = new ArrayList<>();
for (T source : sourceList) {
String id = getFieldId(source);
IndexQuery build = new IndexQueryBuilder().withId(id).withObject(source).build();
queryList.add(build);
}
elasticsearchRestTemplate.bulkIndex(queryList, IndexCoordinates.of(indexName));
}
public static void updateByEntity(T entity, String indexName) {
String id = getFieldId(entity);
Map map = null;
try {
map = BeanUtils.describe(entity);
} catch (Exception e) {
e.printStackTrace();
}
Document document = Document.from(map);
document.setId(id);
// 这里的UpdateQuery需要构造一个Document对象,但是Document对象不能用实体类转化而来
//(可见Document的源码,位于:org.springframework.data.elasticsearch.core.document
// 包下),因此上面才会BeanUtils.describe(entity),将实体类转化成一个map,由map转化
// 为Document对象。
//不加默认false。true表示更新时不存在就插入
UpdateQuery build = UpdateQuery.builder(id)
.withDocAsUpsert(false)
.withDocument(document)
.build();
elasticsearchRestTemplate.update(build, IndexCoordinates.of(indexName));
}
public static void updateByMaps(List list, String indexName) {
List 


