Elasticsearch 创建索引

Elasticsearch 创建索引,第1张

Elasticsearch 创建索引

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

    
    public Map toMapping(T entity) {
        Field[] fields = entity.getClass().getDeclaredFields();
        Map mapping = Maps.newHashMap();
        Map 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 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;
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5696264.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存