一直感觉spring-data-es封装的很迷..调用起来奇奇怪怪 还是封装一层方便自己调用吧
代码语言:javascript复制@Component
public class EsUtil {
private static ElasticsearchRestTemplate elasticsearchRestTemplate;
@Autowired
public EsUtil(ElasticsearchRestTemplate elasticsearchRestTemplate) {
EsUtil.elasticsearchRestTemplate = elasticsearchRestTemplate;
}
/**
* 获取索引对应的别名
*/
public static Set<String> getAlias(String index) {
Preconditions.checkNotNull(index);
final IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(index));
final Map<String, Set<AliasData>> aliases = indexOps.getAliasesForIndex(index);
final Set<AliasData> dataSet = aliases.get(index);
Set<String> set = new HashSet<>(dataSet.size());
dataSet.forEach(aliasData -> set.add(aliasData.getAlias()));
return set;
}
/**
* 为索引添加别名
*
* @param index 真实索引
* @param alias 别名
*/
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);
}
/**
* 为索引删除
*
* @param index 真实索引
* @param alias 别名
*/
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);
}
/**
* 为索引更换别名 旧的换为新的 不会判断旧的是否存在
*
* @param index 真实索引
* @param oldAlias 要删除的别名
* @param newAlias 要新增的别名
*/
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);
}
}