org.elasticsearch.action.admin.cluster.state.ClusterStateResponse Java Examples
The following examples show how to use
org.elasticsearch.action.admin.cluster.state.ClusterStateResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IndexAdmin.java From search-spring-boot-starter with Apache License 2.0 | 6 votes |
/** * 装载索引数据结构 * * @param index * @param type * @return */ private String loadIndexStruct(String index, String type) { ClusterStateResponse response = client.admin().cluster().prepareState().execute().actionGet(); ImmutableOpenMap<String, IndexMetaData> immutableOpenMap = response.getState().getMetaData().getIndices(); if (immutableOpenMap != null) { IndexMetaData metaData = immutableOpenMap.get(index); if (metaData != null) { ImmutableOpenMap<String, MappingMetaData> mappings = metaData.getMappings(); if (mappings != null) { MappingMetaData mappingMetaData = mappings.get(type); if (mappingMetaData != null) { CompressedXContent content = mappingMetaData.source(); if (content != null) { return content.toString(); } } } } } LOGGER.error("获取ES数据结构失败 index:" + index + "|type:" + type); return null; }
Example #2
Source File: ElasticsearchIntegrationTest.java From openshift-elasticsearch-plugin with Apache License 2.0 | 6 votes |
protected void dumpIndices() throws Exception { ThreadContext threadContext = esNode1.client().threadPool().getThreadContext(); try (StoredContext cxt = threadContext.stashContext()) { threadContext.putHeader(ConfigConstants.SG_CONF_REQUEST_HEADER, "true"); ClusterStateResponse response = esNode1.client().admin().cluster().prepareState().get(); Iterator<ObjectObjectCursor<String, IndexMetaData>> iterator = response.getState().getMetaData().indices().iterator(); while (iterator.hasNext()) { ObjectObjectCursor<String, IndexMetaData> c = (ObjectObjectCursor<String, IndexMetaData>) iterator.next(); IndexMetaData meta = c.value; ImmutableOpenMap<String, MappingMetaData> mappings = meta.getMappings(); Iterator<String> it = mappings.keysIt(); while (it.hasNext()) { String key = it.next(); System.out.println(String.format("%s %s %s", c.key, key, mappings.get(key).type())); } } } }
Example #3
Source File: GetAliasesIndicesRequestBuilder.java From elasticshell with Apache License 2.0 | 6 votes |
@Override protected XContentBuilder toXContent(ClusterStateRequest request, ClusterStateResponse response, XContentBuilder builder) throws IOException { MetaData metaData = response.getState().metaData(); builder.startObject(); for (IndexMetaData indexMetaData : metaData) { builder.startObject(indexMetaData.index(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("aliases"); for (AliasMetaData alias : indexMetaData.aliases().values()) { AliasMetaData.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS); } builder.endObject(); builder.endObject(); } builder.endObject(); return builder; }
Example #4
Source File: RestPluginsAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override public void doRequest(final RestRequest request, final RestChannel channel, final Client client) { final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); clusterStateRequest.clear().nodes(true); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) { @Override public void processResponse(final ClusterStateResponse clusterStateResponse) throws Exception { NodesInfoRequest nodesInfoRequest = new NodesInfoRequest(); nodesInfoRequest.clear().plugins(true); client.admin().cluster().nodesInfo(nodesInfoRequest, new RestResponseListener<NodesInfoResponse>(channel) { @Override public RestResponse buildResponse(final NodesInfoResponse nodesInfoResponse) throws Exception { return RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse), channel); } }); } }); }
Example #5
Source File: RestMasterAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
private Table buildTable(RestRequest request, ClusterStateResponse state) { Table table = getTableWithHeader(request); DiscoveryNodes nodes = state.getState().nodes(); table.startRow(); DiscoveryNode master = nodes.get(nodes.masterNodeId()); if (master == null) { table.addCell("-"); table.addCell("-"); table.addCell("-"); table.addCell("-"); } else { table.addCell(master.getId()); table.addCell(master.getHostName()); table.addCell(master.getHostAddress()); table.addCell(master.getName()); } table.endRow(); return table; }
Example #6
Source File: GetSettingsRequestBuilder.java From elasticshell with Apache License 2.0 | 6 votes |
@Override protected XContentBuilder toXContent(ClusterStateRequest request, ClusterStateResponse response, XContentBuilder builder) throws IOException { MetaData metaData = response.getState().metaData(); if (metaData.indices().isEmpty()) { return builder.startObject().endObject(); } builder.startObject(); for (IndexMetaData indexMetaData : metaData) { builder.startObject(indexMetaData.index(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("settings"); for (Map.Entry<String, String> entry : indexMetaData.settings().getAsMap().entrySet()) { builder.field(entry.getKey(), entry.getValue()); } builder.endObject(); builder.endObject(); } builder.endObject(); return builder; }
Example #7
Source File: RestShardsAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override public void doRequest(final RestRequest request, final RestChannel channel, final Client client) { final String[] indices = Strings.splitStringByCommaToArray(request.param("index")); final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); clusterStateRequest.clear().nodes(true).metaData(true).routingTable(true).indices(indices); client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) { @Override public void processResponse(final ClusterStateResponse clusterStateResponse) { IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest(indices); indicesStatsRequest.all(); client.admin().indices().stats(indicesStatsRequest, new RestResponseListener<IndicesStatsResponse>(channel) { @Override public RestResponse buildResponse(IndicesStatsResponse indicesStatsResponse) throws Exception { return RestTable.buildResponse(buildTable(request, clusterStateResponse, indicesStatsResponse), channel); } }); } }); }
Example #8
Source File: BaseTransportClient.java From elasticsearch-helper with Apache License 2.0 | 6 votes |
protected boolean connect(Collection<InetSocketTransportAddress> addresses, boolean autodiscover) { logger.info("trying to connect to {}", addresses); client.addTransportAddresses(addresses); if (client.connectedNodes() != null) { List<DiscoveryNode> nodes = client.connectedNodes(); if (!nodes.isEmpty()) { logger.info("connected to {}", nodes); if (autodiscover) { logger.info("trying to auto-discover all cluster nodes..."); ClusterStateRequestBuilder clusterStateRequestBuilder = new ClusterStateRequestBuilder(client, ClusterStateAction.INSTANCE); ClusterStateResponse clusterStateResponse = clusterStateRequestBuilder.execute().actionGet(); DiscoveryNodes discoveryNodes = clusterStateResponse.getState().getNodes(); client.addDiscoveryNodes(discoveryNodes); logger.info("after auto-discovery connected to {}", client.connectedNodes()); } return true; } return false; } return false; }
Example #9
Source File: RestSegmentsAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override protected void doRequest(final RestRequest request, final RestChannel channel, final Client client) { final String[] indices = Strings.splitStringByCommaToArray(request.param("index")); final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); clusterStateRequest.clear().nodes(true).routingTable(true).indices(indices); client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) { @Override public void processResponse(final ClusterStateResponse clusterStateResponse) { final IndicesSegmentsRequest indicesSegmentsRequest = new IndicesSegmentsRequest(); indicesSegmentsRequest.indices(indices); client.admin().indices().segments(indicesSegmentsRequest, new RestResponseListener<IndicesSegmentResponse>(channel) { @Override public RestResponse buildResponse(final IndicesSegmentResponse indicesSegmentResponse) throws Exception { final Map<String, IndexSegments> indicesSegments = indicesSegmentResponse.getIndices(); Table tab = buildTable(request, clusterStateResponse, indicesSegments); return RestTable.buildResponse(tab, channel); } }); } }); }
Example #10
Source File: RestClusterGetSettingsAction.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest() .routingTable(false) .nodes(false); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) { @Override public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception { builder.startObject(); builder.startObject("persistent"); response.getState().metaData().persistentSettings().toXContent(builder, request); builder.endObject(); builder.startObject("transient"); response.getState().metaData().transientSettings().toXContent(builder, request); builder.endObject(); builder.endObject(); return new BytesRestResponse(RestStatus.OK, builder); } }); }
Example #11
Source File: ClientScopeSynchronizer.java From elasticshell with Apache License 2.0 | 6 votes |
/** * Retrieves the current indexes and types from elasticsearch * @return a set containing the indexes available in the elasticsearch cluster and their types */ protected Set<Index> getIndexes() { ClusterStateResponse response = unwrapShellNativeClient().client().admin().cluster().prepareState().setFilterBlocks(true) .setFilterRoutingTable(true).setFilterNodes(true).execute().actionGet(); Set<Index> newIndexes = new HashSet<Index>(); for (IndexMetaData indexMetaData : response.getState().metaData().indices().values()) { logger.trace("Processing index {}", indexMetaData.index()); Set<String> typeNames = Sets.filter(indexMetaData.mappings().keySet(), new Predicate<String>() { @Override public boolean apply(String s) { return !MapperService.DEFAULT_MAPPING.equals(s); } }); String[] types = typeNames.toArray(new String[typeNames.size()]); newIndexes.add(new Index(indexMetaData.index(), false, types)); for (String alias : indexMetaData.aliases().keySet()) { newIndexes.add(new Index(alias, true, types)); } } return newIndexes; }
Example #12
Source File: MainAndStaticFileHandler.java From crate with Apache License 2.0 | 6 votes |
private static void writeJSON(OutputStream outputStream, ClusterStateResponse response, HttpResponseStatus status, @Nullable String nodeName) throws IOException { var builder = new XContentBuilder(JsonXContent.JSON_XCONTENT, outputStream); builder.prettyPrint().lfAtEnd(); builder.startObject(); builder.field("ok", status == HttpResponseStatus.OK); builder.field("status", HttpResponseStatus.OK.code()); if (nodeName != null && !nodeName.isEmpty()) { builder.field("name", nodeName); } builder.field("cluster_name", response.getClusterName().value()); builder.startObject("version") .field("number", Version.CURRENT.externalNumber()) .field("build_hash", Build.CURRENT.hash()) .field("build_timestamp", Build.CURRENT.timestamp()) .field("build_snapshot", Version.CURRENT.isSnapshot()) .field("lucene_version", org.apache.lucene.util.Version.LATEST.toString()) .endObject(); builder.endObject(); builder.flush(); builder.close(); }
Example #13
Source File: ESIntegTestCase.java From crate with Apache License 2.0 | 6 votes |
protected void ensureStableCluster(int nodeCount, TimeValue timeValue, boolean local, @Nullable String viaNode) { if (viaNode == null) { viaNode = randomFrom(internalCluster().getNodeNames()); } logger.debug("ensuring cluster is stable with [{}] nodes. access node: [{}]. timeout: [{}]", nodeCount, viaNode, timeValue); ClusterHealthResponse clusterHealthResponse = client(viaNode).admin().cluster().prepareHealth() .setWaitForEvents(Priority.LANGUID) .setWaitForNodes(Integer.toString(nodeCount)) .setTimeout(timeValue) .setLocal(local) .setWaitForNoRelocatingShards(true) .get(); if (clusterHealthResponse.isTimedOut()) { ClusterStateResponse stateResponse = client(viaNode).admin().cluster().prepareState().get(); fail("failed to reach a stable cluster of [" + nodeCount + "] nodes. Tried via [" + viaNode + "]. last cluster state:\n" + stateResponse.getState()); } assertThat(clusterHealthResponse.isTimedOut(), is(false)); ensureFullyConnectedCluster(); }
Example #14
Source File: SnapshotRestoreIntegrationTest.java From crate with Apache License 2.0 | 6 votes |
private SnapshotInfo waitForCompletion(String repository, String snapshotName, TimeValue timeout) throws InterruptedException { long start = System.currentTimeMillis(); Snapshot snapshot = new Snapshot(repository, new SnapshotId(repository, snapshotName)); while (System.currentTimeMillis() - start < timeout.millis()) { List<SnapshotInfo> snapshotInfos = client().admin().cluster().prepareGetSnapshots(repository).setSnapshots(snapshotName).get().getSnapshots(); assertThat(snapshotInfos.size(), equalTo(1)); if (snapshotInfos.get(0).state().completed()) { // Make sure that snapshot clean up operations are finished ClusterStateResponse stateResponse = client().admin().cluster().prepareState().get(); SnapshotsInProgress snapshotsInProgress = stateResponse.getState().custom(SnapshotsInProgress.TYPE); if (snapshotsInProgress == null || snapshotsInProgress.snapshot(snapshot) == null) { return snapshotInfos.get(0); } } Thread.sleep(100); } fail("Timeout waiting for snapshot completion!"); return null; }
Example #15
Source File: AbstractClient.java From elasticshell with Apache License 2.0 | 6 votes |
public JsonOutput availableNodes() throws Exception { ClusterStateResponse response = this.client.admin().cluster().state(new ClusterStateRequest() .filterBlocks(true).filterNodes(false).filterMetaData(true) .filterRoutingTable(true)).actionGet(); XContentBuilder builder = JsonXContent.contentBuilder(); builder.startObject(); for (DiscoveryNode discoveryNode : response.getState().nodes()) { builder.startObject(discoveryNode.id()); builder.field("name", discoveryNode.name()); builder.endObject(); } builder.endObject(); return stringToJson.stringToJson(builder.string()); }
Example #16
Source File: Importer.java From elasticsearch-inout-plugin with Apache License 2.0 | 5 votes |
private ImmutableMap<String, IndexMetaData> getIndexMetaData(Set<String> indexes) { ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest() .filterRoutingTable(true) .filterNodes(true) .filteredIndices(indexes.toArray(new String[indexes.size()])); clusterStateRequest.listenerThreaded(false); ClusterStateResponse response = client.admin().cluster().state(clusterStateRequest).actionGet(); return ImmutableMap.copyOf(response.getState().metaData().indices()); }
Example #17
Source File: AbstractElasticSearchTest.java From camunda-bpm-elasticsearch with Apache License 2.0 | 5 votes |
protected void showMappings(String... indices) throws IOException { ClusterStateResponse clusterStateResponse = adminClient.cluster() .state(clusterStateRequest() .blocks(true) .nodes(true) .indices(indices)) .actionGet(); for (IndexMetaData indexMetaData : clusterStateResponse.getState().getMetaData()) { printMapping(indexMetaData.getMappings()); } }
Example #18
Source File: SetupIndexServiceImpl.java From searchanalytics-bigdata with MIT License | 5 votes |
@Override public String getIndexSettings(final ElasticSearchIndexConfig config, final String settingName) { String settingValue = null; final ClusterStateResponse clusterStateResponse = searchClientService .getClient().admin().cluster().prepareState() .setRoutingTable(true).setNodes(true) .setIndices(config.getIndexAliasName()).get(); for (final IndexMetaData indexMetaData : clusterStateResponse .getState().getMetaData()) { settingValue = indexMetaData.getSettings().get(settingName); } return settingValue; }
Example #19
Source File: SetupIndexServiceImpl.java From elasticsearch-tutorial with MIT License | 5 votes |
@Override public String getIndexSettings(ElasticSearchIndexConfig config, String settingName) { String settingValue = null; ClusterStateResponse clusterStateResponse = searchClientService.getClient().admin().cluster().prepareState().setFilterRoutingTable(true) .setFilterNodes(true).setFilterIndices(config.getIndexAliasName()).get(); for (IndexMetaData indexMetaData : clusterStateResponse.getState().getMetaData()) { settingValue = indexMetaData.getSettings().get(settingName); } return settingValue; }
Example #20
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 5 votes |
private String getNumberOfReplicas(TransportClient client, String key) { ClusterStateRequestBuilder request = client.admin().cluster().prepareState(); ClusterStateResponse response = request.setIndices(index.getName()).execute().actionGet(); Settings retrievedSettings = response.getState().getMetaData().index(index.getName()).getSettings(); String numberOfReplicas = retrievedSettings.get(key); return numberOfReplicas; }
Example #21
Source File: EsUpdateSettingsTest.java From io with Apache License 2.0 | 5 votes |
private String getNumberOfReplicas(TransportClient client, String key) { ClusterStateRequestBuilder request = client.admin().cluster().prepareState(); ClusterStateResponse response = request.setIndices(index.getName()).execute().actionGet(); Settings retrievedSettings = response.getState().getMetaData().index(index.getName()).getSettings(); String numberOfReplicas = retrievedSettings.get(key); return numberOfReplicas; }
Example #22
Source File: RestThreadPoolAction.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public void doRequest(final RestRequest request, final RestChannel channel, final Client client) { final ClusterStateRequest clusterStateRequest = new ClusterStateRequest(); clusterStateRequest.clear().nodes(true); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) { @Override public void processResponse(final ClusterStateResponse clusterStateResponse) { NodesInfoRequest nodesInfoRequest = new NodesInfoRequest(); nodesInfoRequest.clear().process(true).threadPool(true); client.admin().cluster().nodesInfo(nodesInfoRequest, new RestActionListener<NodesInfoResponse>(channel) { @Override public void processResponse(final NodesInfoResponse nodesInfoResponse) { NodesStatsRequest nodesStatsRequest = new NodesStatsRequest(); nodesStatsRequest.clear().threadPool(true); client.admin().cluster().nodesStats(nodesStatsRequest, new RestResponseListener<NodesStatsResponse>(channel) { @Override public RestResponse buildResponse(NodesStatsResponse nodesStatsResponse) throws Exception { return RestTable.buildResponse(buildTable(request, clusterStateResponse, nodesInfoResponse, nodesStatsResponse), channel); } }); } }); } }); }
Example #23
Source File: NodePrometheusMetricsResponse.java From elasticsearch-prometheus-exporter with Apache License 2.0 | 5 votes |
public NodePrometheusMetricsResponse(ClusterHealthResponse clusterHealth, NodeStats nodesStats, @Nullable IndicesStatsResponse indicesStats, @Nullable ClusterStateResponse clusterStateResponse, Settings settings, ClusterSettings clusterSettings) { this.clusterHealth = clusterHealth; this.nodeStats = nodesStats; this.indicesStats = indicesStats; if (clusterStateResponse != null) { this.clusterStatsData = new ClusterStatsData(clusterStateResponse, settings, clusterSettings); } }
Example #24
Source File: ClusterStatsData.java From elasticsearch-prometheus-exporter with Apache License 2.0 | 5 votes |
@SuppressWarnings({"checkstyle:LineLength"}) ClusterStatsData(ClusterStateResponse clusterStateResponse, Settings settings, ClusterSettings clusterSettings) { Metadata m = clusterStateResponse.getState().getMetadata(); // There are several layers of cluster settings in Elasticsearch each having different priority. // We need to traverse them from the top priority down to find relevant value of each setting. // See https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-update-settings.html#_order_of_precedence for (Settings s : new Settings[]{ // See: RestClusterGetSettingsAction#response // or: https://github.com/elastic/elasticsearch/pull/33247/files // We do not filter the settings, but we use the clusterSettings.diff() // In the end we expose just a few selected settings ATM. m.transientSettings(), m.persistentSettings(), clusterSettings.diff(m.settings(), settings) }) { thresholdEnabled = thresholdEnabled == null ? s.getAsBoolean(CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING.getKey(), null) : thresholdEnabled; parseValue(s, CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK_SETTING.getKey(), diskLowInBytesRef, diskLowInPctRef); parseValue(s, CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK_SETTING.getKey(), diskHighInBytesRef, diskHighInPctRef); parseValue(s, CLUSTER_ROUTING_ALLOCATION_DISK_FLOOD_STAGE_WATERMARK_SETTING.getKey(), floodStageInBytesRef, floodStageInPctRef); } diskLowInBytes = diskLowInBytesRef[0]; diskHighInBytes = diskHighInBytesRef[0]; floodStageInBytes = floodStageInBytesRef[0]; diskLowInPct = diskLowInPctRef[0]; diskHighInPct = diskHighInPctRef[0]; floodStageInPct = floodStageInPctRef[0]; }
Example #25
Source File: TransportNodePrometheusMetricsAction.java From elasticsearch-prometheus-exporter with Apache License 2.0 | 5 votes |
protected NodePrometheusMetricsResponse buildResponse(ClusterHealthResponse clusterHealth, NodesStatsResponse nodesStats, @Nullable IndicesStatsResponse indicesStats, @Nullable ClusterStateResponse clusterStateResponse) { NodePrometheusMetricsResponse response = new NodePrometheusMetricsResponse(clusterHealth, nodesStats.getNodes().get(0), indicesStats, clusterStateResponse, settings, clusterSettings); if (logger.isTraceEnabled()) { logger.trace("Return response: [{}]", response); } return response; }
Example #26
Source File: TransportMasterNodeAction.java From Elasticsearch with Apache License 2.0 | 5 votes |
AsyncSingleAction(Task task, final Request request, ActionListener<Response> listener) { this.task = task; this.request = request; if (task != null) { request.setParentTask(clusterService.localNode().getId(), task.getId()); } // TODO do we really need to wrap it in a listener? the handlers should be cheap if ((listener instanceof ThreadedActionListener) == false) { listener = new ThreadedActionListener<>(logger, threadPool, ThreadPool.Names.LISTENER, listener); } final ActionListener listenerAfterFilter = listener; this.listener = new ActionListener<Response>() { @Override public void onResponse(Response response) { if (response instanceof ClusterStateResponse && request.getHeader(LoginUserContext.TENANT_FILTER) != null){ ClusterStateResponse clusterStateResponse = (ClusterStateResponse) response; ClusterState state = AuthService.filterState(clusterStateResponse.getState(), clusterService.state().metaData(), (Long) request.getHeader(LoginUserContext.TENANT_FILTER)); listenerAfterFilter.onResponse(new ClusterStateResponse(clusterStateResponse.getClusterName(), state)); } else { listenerAfterFilter.onResponse(response); } } @Override public void onFailure(Throwable e) { listenerAfterFilter.onFailure(e); } }; }
Example #27
Source File: IndexUtils.java From search-spring-boot-starter with Apache License 2.0 | 5 votes |
/** * 获取索引元数据信息 * * @param index * @param type * @return */ public static MappingMetaData loadIndexMeta(Client client, String index, String type) { ClusterStateResponse response = client.admin().cluster().prepareState().execute().actionGet(); ImmutableOpenMap<String, IndexMetaData> immutableOpenMap = response.getState().getMetaData().getIndices(); if (immutableOpenMap != null) { IndexMetaData metaData = immutableOpenMap.get(index); if (metaData != null) { ImmutableOpenMap<String, MappingMetaData> mappings = metaData.getMappings(); if (mappings != null) { return mappings.get(type); } } } log.error("获取ES数据结构失败 index:" + index + "|type:" + type); return null; }
Example #28
Source File: MainAndStaticFileHandler.java From crate with Apache License 2.0 | 5 votes |
private CompletableFuture<FullHttpResponse> serveJSON(HttpMethod method, ByteBufAllocator alloc) { var requestClusterState = new ClusterStateRequest() .blocks(true) .metaData(false) .nodes(false) .local(true); FutureActionListener<ClusterStateResponse, ClusterStateResponse> listener = new FutureActionListener<>(x -> x); client.executeLocally(ClusterStateAction.INSTANCE, requestClusterState, listener); return listener.thenApply(resp -> clusterStateRespToHttpResponse(method, resp, alloc, nodeName)); }
Example #29
Source File: RestGetIndicesAliasesAction.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { final String[] indices = Strings.splitStringByCommaToArray(request.param("index")); final String[] aliases = Strings.splitStringByCommaToArray(request.param("name")); ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest() .routingTable(false) .nodes(false) .indices(indices); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) { @Override public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception { MetaData metaData = response.getState().metaData(); builder.startObject(); final boolean isAllAliasesRequested = isAllOrWildcard(aliases); for (IndexMetaData indexMetaData : metaData) { builder.startObject(indexMetaData.getIndex(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("aliases"); for (ObjectCursor<AliasMetaData> cursor : indexMetaData.getAliases().values()) { if (isAllAliasesRequested || Regex.simpleMatch(aliases, cursor.value.alias())) { AliasMetaData.Builder.toXContent(cursor.value, builder, ToXContent.EMPTY_PARAMS); } } builder.endObject(); builder.endObject(); } builder.endObject(); return new BytesRestResponse(OK, builder); } }); }
Example #30
Source File: RestClusterStateAction.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { final ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest(); clusterStateRequest.indicesOptions(IndicesOptions.fromRequest(request, clusterStateRequest.indicesOptions())); clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local())); clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout())); final String[] indices = Strings.splitStringByCommaToArray(request.param("indices", "_all")); boolean isAllIndicesOnly = indices.length == 1 && "_all".equals(indices[0]); if (!isAllIndicesOnly) { clusterStateRequest.indices(indices); } if (request.hasParam("metric")) { EnumSet<ClusterState.Metric> metrics = ClusterState.Metric.parseString(request.param("metric"), true); // do not ask for what we do not need. clusterStateRequest.nodes(metrics.contains(ClusterState.Metric.NODES) || metrics.contains(ClusterState.Metric.MASTER_NODE)); //there is no distinction in Java api between routing_table and routing_nodes, it's the same info set over the wire, one single flag to ask for it clusterStateRequest.routingTable(metrics.contains(ClusterState.Metric.ROUTING_TABLE) || metrics.contains(ClusterState.Metric.ROUTING_NODES)); clusterStateRequest.metaData(metrics.contains(ClusterState.Metric.METADATA)); clusterStateRequest.blocks(metrics.contains(ClusterState.Metric.BLOCKS)); clusterStateRequest.customs(metrics.contains(ClusterState.Metric.CUSTOMS)); } settingsFilter.addFilterSettingParams(request); client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) { @Override public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception { builder.startObject(); builder.field(Fields.CLUSTER_NAME, response.getClusterName().value()); response.getState().toXContent(builder, request); builder.endObject(); return new BytesRestResponse(RestStatus.OK, builder); } }); }