diff --git a/server/src/main/java/org/opensearch/indices/NodeIndicesStats.java b/server/src/main/java/org/opensearch/indices/NodeIndicesStats.java index 3aae9c07b1c04..203e30a24bd56 100644 --- a/server/src/main/java/org/opensearch/indices/NodeIndicesStats.java +++ b/server/src/main/java/org/opensearch/indices/NodeIndicesStats.java @@ -299,33 +299,27 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.startObject(Fields.INDICES); stats.toXContent(builder, params); - if (Fields.INDICES.equals(level)) { - if (statsByIndex == null && statsByShard != null) { - statsByIndex = createStatsByIndex(statsByShard); - } + if ("indices".equals(level)) { + Map indexStats = createStatsByIndex(); builder.startObject(Fields.INDICES); - if (statsByIndex != null) { - for (Map.Entry entry : statsByIndex.entrySet()) { - builder.startObject(entry.getKey().getName()); - entry.getValue().toXContent(builder, params); - builder.endObject(); - } + for (Map.Entry entry : indexStats.entrySet()) { + builder.startObject(entry.getKey().getName()); + entry.getValue().toXContent(builder, params); + builder.endObject(); } builder.endObject(); - } else if (Fields.SHARDS.equals(level)) { + } else if ("shards".equals(level)) { builder.startObject("shards"); - if (statsByShard != null) { - for (Map.Entry> entry : statsByShard.entrySet()) { - builder.startArray(entry.getKey().getName()); - for (IndexShardStats indexShardStats : entry.getValue()) { - builder.startObject().startObject(String.valueOf(indexShardStats.getShardId().getId())); - for (ShardStats shardStats : indexShardStats.getShards()) { - shardStats.toXContent(builder, params); - } - builder.endObject().endObject(); + for (Map.Entry> entry : statsByShard.entrySet()) { + builder.startArray(entry.getKey().getName()); + for (IndexShardStats indexShardStats : entry.getValue()) { + builder.startObject().startObject(String.valueOf(indexShardStats.getShardId().getId())); + for (ShardStats shardStats : indexShardStats.getShards()) { + shardStats.toXContent(builder, params); } - builder.endArray(); + builder.endObject().endObject(); } + builder.endArray(); } builder.endObject(); } @@ -351,6 +345,23 @@ private Map createStatsByIndex(Map createStatsByIndex() { + Map statsMap = new HashMap<>(); + for (Map.Entry> entry : statsByShard.entrySet()) { + if (!statsMap.containsKey(entry.getKey())) { + statsMap.put(entry.getKey(), new CommonStats()); + } + + for (IndexShardStats indexShardStats : entry.getValue()) { + for (ShardStats shardStats : indexShardStats.getShards()) { + statsMap.get(entry.getKey()).add(shardStats.getStats()); + } + } + } + + return statsMap; + } + public List getShardStats(Index index) { if (statsByShard == null) { return null;