Elasticsearch 创建索引 Java 实现

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

你可能感兴趣的:(elasticsearch,大数据,big,data)