forked from kidgrow-microservices-platform

克 刘
2020-03-16 549148d90d41a3320bd36d469fd690354c78de58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package com.kidgrow.admin.service.impl;
 
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.kidgrow.admin.model.IndexDto;
import com.kidgrow.admin.model.IndexVo;
import com.kidgrow.admin.service.IIndexService;
import com.kidgrow.common.model.PageResult;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.stats.IndexStats;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequestBuilder;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.search.stats.SearchStats;
import org.elasticsearch.index.shard.DocsStats;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: 索引<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/24 13:47 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
@Service
public class IndexServiceImpl implements IIndexService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
 
    @Override
    public void create(IndexDto indexDto) {
        // setting
        Settings settings = Settings.builder()
                .put("index.number_of_shards", indexDto.getNumberOfShards())
                .put("index.number_of_replicas", indexDto.getNumberOfReplicas())
                .build();
        CreateIndexRequestBuilder builder = elasticsearchTemplate.getClient().admin()
                .indices()
                .prepareCreate(indexDto.getIndexName())
                .setSettings(settings);
        if (StrUtil.isNotEmpty(indexDto.getType()) && StrUtil.isNotEmpty(indexDto.getMappingsSource())) {
            //mappings
            builder.addMapping(indexDto.getType(), indexDto.getMappingsSource(), XContentType.JSON);
        }
        builder.get();
    }
 
    @Override
    public void delete(String indexName) {
        elasticsearchTemplate.getClient().admin().indices()
                .prepareDelete(indexName)
                .execute().actionGet();
    }
 
    @Override
    public PageResult<IndexVo> list(String queryStr, String... indices) {
        IndicesStatsRequestBuilder indicesBuilder = elasticsearchTemplate.getClient().admin().indices()
                .prepareStats(indices);
        if (StrUtil.isNotEmpty(queryStr)) {
            indicesBuilder.setIndices(queryStr);
        }
        List<IndexVo> indexList = new ArrayList<>();
        try {
            IndicesStatsResponse response = indicesBuilder.execute().actionGet();
            Map<String, IndexStats> indicesMap = response.getIndices();
            for(IndexStats stat : indicesMap.values()) {
                IndexVo vo = new IndexVo();
                vo.setIndexName(stat.getIndex());
                //获取文档数据
                DocsStats docsStats = stat.getTotal().getDocs();
                vo.setDocsCount(docsStats.getCount());
                vo.setDocsDeleted(docsStats.getDeleted());
                //获取存储数据
                vo.setStoreSizeInBytes(getKB(stat.getTotal().getStore().getSizeInBytes()));
                //获取查询数据
                SearchStats.Stats searchStats = stat.getTotal().getSearch().getTotal();
                vo.setQueryCount(searchStats.getQueryCount());
                vo.setQueryTimeInMillis(searchStats.getQueryTimeInMillis() / 1000D);
 
                indexList.add(vo);
            }
        } catch (IndexNotFoundException e) {}
        return PageResult.<IndexVo>builder().data(indexList).code(0).build();
    }
 
    /**
     * bytes 转换为 kb
     */
    private Double getKB(Long bytes) {
        if (bytes == null) {
            return 0D;
        }
        return bytes / 1024D;
    }
 
    @Override
    public Map<String, Object> show(String indexName) {
        ImmutableOpenMap<String, IndexMetaData>  stat = elasticsearchTemplate.getClient().admin().cluster()
                .prepareState().setIndices(indexName).execute().actionGet()
                .getState()
                .getMetaData()
                .getIndices();
 
        IndexMetaData indexMetaData = stat.get(indexName);
        //获取settings数据
        String settingsStr = indexMetaData.getSettings().toString();
        Object settingsObj = null;
        if (StrUtil.isNotEmpty(settingsStr)) {
            settingsObj = JSONObject.parse(settingsStr);
        }
 
        ImmutableOpenMap<String, MappingMetaData> mappOpenMap = indexMetaData.getMappings();
        ImmutableOpenMap<String, AliasMetaData> aliasesOpenMap = indexMetaData.getAliases();
        Map<String, Object> result = new HashMap<>(1);
        Map<String, Object> indexMap = new HashMap<>(3);
        Map<String, Object> mappMap = new HashMap<>(mappOpenMap.size());
        Map<String, Object> aliasesMap = new HashMap<>(aliasesOpenMap.size());
        indexMap.put("aliases", aliasesMap);
        indexMap.put("settings", settingsObj);
        indexMap.put("mappings", mappMap);
        result.put(indexName, indexMap);
        //获取mappings数据
        for (ObjectCursor<String> key : mappOpenMap.keys()) {
            MappingMetaData data = mappOpenMap.get(key.value);
            Map<String, Object> dataMap = data.getSourceAsMap();
            mappMap.put(key.value, dataMap);
        }
        //获取aliases数据
        for (ObjectCursor<String> key : aliasesOpenMap.keys()) {
            AliasMetaData data = aliasesOpenMap.get(key.value);
            aliasesMap.put(key.value, data.alias());
        }
        return result;
    }
}