elasticsearch 创建、删除索引

5 篇文章 0 订阅
0 篇文章 0 订阅
public class EsAdmin {

    private TransportClient client;

    public EsAdmin(TransportClient client) {
        this.client = client;
    }

    @Override
    public void createIndex(String index, String type, Map<String, String> mappings) throws IOException {
        IndicesAdminClient adminClient = client.admin().indices();
        boolean indexExists = adminClient.exists(new IndicesExistsRequest(index)).actionGet().isExists();
        if (!indexExists) {
            String result = adminClient.create(new CreateIndexRequest(index)).actionGet().index();
            if (StringUtils.isEmpty(result)) {
                throw new ProcessException("createIndex failed: " + index);
            }
        }

        boolean typeExists = adminClient.typesExists(new TypesExistsRequest(new String[]{index}, new String[]{type})).actionGet().isExists();
        if (!typeExists) {
            XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("properties");
            for (Map.Entry<String, String> entry : mappings.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                xContentBuilder.startObject(key)
                        .field("type", value);
                if ("text".equalsIgnoreCase(value)) {
                    xContentBuilder.startObject("fields")
                            .startObject("keyword")
                            .field("type", "keyword")
                            .endObject()
                            .endObject();
                }
                xContentBuilder.endObject();
            }
            xContentBuilder.endObject()
                    .endObject();
            String json = Strings.toString(xContentBuilder);

            PutMappingRequest mapping = Requests.putMappingRequest(index).type(type).source(xContentBuilder);
            boolean acknowledged = adminClient.putMapping(mapping).actionGet().isAcknowledged();
            if (!acknowledged) {
                throw new ProcessException(String.format("createType failed: index=%s, type=%s, mappings=%s", index, type, json));
            }
        }
    }

    @Override
    public void deleteIndex(String index) {
        IndicesAdminClient adminClient = client.admin().indices();
        boolean acknowledged = adminClient.delete(new DeleteIndexRequest(index)).actionGet().isAcknowledged();
        if (!acknowledged) {
            throw new ProcessException(String.format("deleteIndex failed: index=%s", index));
        }
    }

    @Override
    public long count(String index, String type) {
        SearchResponse searchResponse = client.prepareSearch(index).setTypes(type)
                .addAggregation(AggregationBuilders.count("count").field("_id"))
                .get();
        long count = ((InternalValueCount) (searchResponse.getAggregations().get("count"))).getValue();
        return count;
    }

    @Override
    public List<EsData> exportData(String index, String type) {
        int from = 0;
        int unit = 1000;
        List<SearchHit> list = new ArrayList<>();
        List<SearchHit> tmpList;
        do {
            SearchHits hits = client.prepareSearch(index).setTypes(type)
                    .setQuery(QueryBuilders.matchAllQuery())
                    .setFrom(from).setSize(unit)
                    .get().getHits();
            tmpList = Arrays.asList(hits.getHits());
            list.addAll(tmpList);
            from += hits.getTotalHits() + 1;
        } while (!tmpList.isEmpty());
        List<EsData> export = list.stream().map(e -> {
            return new EsData(e.getId(), e.getSourceAsMap());
        }).collect(Collectors.toList());
        return export;
    }

    @Override
    public void importData(String index, String type, List<EsData> data) {
        for (EsData esData : data) {
            IndexResponse response = client.prepareIndex(index, type)
                    .setId(esData.getId())
                    .setSource(esData.getData())
                    .get();
            if (!(RestStatus.CREATED.equals(response.status()) || RestStatus.OK.equals(response.status()))) {
                throw new EsException();
            }
        }
    }
}

public class EsData implements Serializable {

    private String id;
    private Map<String, Object> data = new HashMap<>();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    public EsData() {
    }

    public EsData(String id, Map<String, Object> data) {
        this.id = id;
        this.data = data;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值