Elasticsearch 创建索引 Java 实现

本文详细介绍了如何使用Java进行Elasticsearch的索引操作,包括创建索引、检查索引存在性以及删除索引等关键步骤,旨在帮助开发者更好地管理和维护Elasticsearch数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建索引,支持实体转map

public boolean createIndex(T entity) {
        String index = indexName(entity);
        try {
            CreateIndexRequest request = new CreateIndexRequest(index);
            request.mapping(toMapping(entity));
            client.indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("索引创建失败,Exception:", e);
        }
        return false;
    }

    /**
     * 文档类型创建
     *
     * @param entity
     * @return
     */
    public Map toMapping(T entity) {
        Field[] fields = entity.getClass().getDeclaredFields();
        Map<String, Object> mapping = Maps.newHashMap();
        Map<String, Object> fieldMap = Maps.newHashMap();
        mapping.put("properties", fieldMap);
        Stream.of(fields).forEach(field -> {
            if (field.isAnnotationPresent(com.zhongfu.adm.es.annotations.Field.class)) {
                com.zhongfu.adm.es.annotations.Field annotation =
                        field.getAnnotation(com.zhongfu.adm.es.annotations.Field.class);
                Map<String, Object> fieldType = new FieldMap();
                String name = StringUtils.hasLength(annotation.name()) ? annotation.name() : field.getName();
                fieldMap.put(name, fieldType);
                fieldType.put("type", annotation.type().name());
                fieldType.put("analyzer", annotation.analyzer());
                fieldType.put("search_analyzer", annotation.searchAnalyzer());
                fieldType.put("index", annotation.index());
            } else {
                fieldMap.put(field.getName(), FieldType.AUTO);
            }
        });
        return mapping;
    }

2.判断索引是否存在

public boolean isExistsIndex(String... indices) {
        try {
            GetIndexRequest request = new GetIndexRequest(indices);
            return client.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("请求失败,Exception:", e);
        }
        return false;
    }

3.删除索引

public boolean deleteIndex(String... indices) {
        try {
            DeleteIndexRequest request = new DeleteIndexRequest(indices);
            AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
            return response.isAcknowledged();
        } catch (IOException e) {
            log.error("索引删除失败,Exception:", e);
        }
        return false;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值