下面列出了怎么用org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse的API类实例代码及写法,或者点击链接到github查看源代码。
public void updateMappingOnMaster(String index, String type, Mapping mappingUpdate, final TimeValue timeout, final MappingUpdateListener listener) {
final PutMappingRequestBuilder request = updateMappingRequest(index, type, mappingUpdate, timeout);
if (listener == null) {
request.execute();
} else {
final ActionListener<PutMappingResponse> actionListener = new ActionListener<PutMappingResponse>() {
@Override
public void onResponse(PutMappingResponse response) {
if (response.isAcknowledged()) {
listener.onMappingUpdate();
} else {
listener.onFailure(new TimeoutException("Failed to acknowledge the mapping response within [" + timeout + "]"));
}
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
};
request.execute(actionListener);
}
}
private static PutMappingResponse internalPutMapping(Client client, String indexName, IElasticSearchMapping mapping) throws IOException {
final PutMappingRequest putMappingRequest = new PutMappingRequest(indexName)
.type(mapping.getIndexType())
.source(mapping.getMapping().string());
final PutMappingResponse putMappingResponse = client
.admin()
.indices()
.putMapping(putMappingRequest)
.actionGet();
if(log.isDebugEnabled()) {
log.debug("PutMappingResponse: isAcknowledged {}", putMappingResponse.isAcknowledged());
}
return putMappingResponse;
}
private static PutMappingResponse internalPutMapping(Client client, String indexName, IElasticSearchMapping mapping) throws IOException {
final PutMappingRequest putMappingRequest = new PutMappingRequest(indexName)
.type(mapping.getIndexType())
.source(mapping.getMapping().string());
final PutMappingResponse putMappingResponse = client
.admin()
.indices()
.putMapping(putMappingRequest)
.actionGet();
if(log.isDebugEnabled()) {
log.debug("PutMappingResponse: isAcknowledged {}", putMappingResponse.isAcknowledged());
}
return putMappingResponse;
}
@Override
public void putMapping(List<String> indices, String type, JsonObject source, MappingOptions options, Handler<AsyncResult<Void>> resultHandler) {
final PutMappingRequestBuilder builder = PutMappingAction.INSTANCE.newRequestBuilder(service.getClient())
.setIndices(indices.toArray(new String[indices.size()]))
.setType(type)
.setSource(source.encode(), XContentType.JSON);
builder.execute(new ActionListener<PutMappingResponse>() {
@Override
public void onResponse(PutMappingResponse putMappingResponse) {
resultHandler.handle(Future.succeededFuture());
}
@Override
public void onFailure(Exception e) {
resultHandler.handle(Future.failedFuture(e));
}
});
}
@Before
public void setUp() throws Exception {
if (client.admin().indices().prepareExists(getIndexName()).execute().actionGet().isExists()) {
DeleteIndexResponse deleteIndexResponse = client.admin().indices().prepareDelete(getIndexName())
.execute().actionGet();
Assert.assertTrue(deleteIndexResponse.isAcknowledged());
}
CreateIndexResponse createIndexResponse = client.admin().indices().prepareCreate(getIndexName())
.execute().actionGet();
Assert.assertTrue(createIndexResponse.isAcknowledged());
for (Map.Entry<String, String> esMapping : getEsMappings().entrySet()) {
String esMappingSource = IOUtils.toString(
AbstractEsTest.class.getClassLoader().getResourceAsStream(esMapping.getValue()));
PutMappingResponse putMappingResponse = client.admin().indices().preparePutMapping(getIndexName())
.setType(esMapping.getKey()).setSource(esMappingSource).execute().actionGet();
Assert.assertTrue(putMappingResponse.isAcknowledged());
}
}
/**
* 创建索引以及映射mapping,并给索引某些字段指定iK分词,以后向该索引中查询时,就会用ik分词。
* @Author lihaodong
* @Description
* @Date 20:19 2018/12/21
* @Param [indexName, esType]
* @return boolean
**/
public static boolean createIndex(String indexName, String esType) {
if (!isIndexExist(indexName)) {
log.info("Index is not exits!");
}
//创建映射
XContentBuilder mapping = null;
try {
mapping = XContentFactory.jsonBuilder()
.startObject()
.startObject("properties") // .startObject("m_id").field("type","keyword").endObject()
// title:字段名, type:文本类型 analyzer :分词器类型
.startObject("id").field("type", "text").field("analyzer", "standard").endObject() //该字段添加的内容,查询时将会使用ik_smart分词
.startObject("name").field("type", "text").field("analyzer", "standard").endObject() //ik_smart ik_max_word standard
.startObject("message").field("type", "text").field("analyzer", "standard").endObject()
.startObject("price").field("type", "float").endObject()
.startObject("creatDate").field("type", "date").endObject()
.endObject()
.endObject();
} catch (IOException e) {
log.error("执行建立失败:{}",e.getMessage());
}
//index:索引名 type:类型名
PutMappingRequest putmap = Requests.putMappingRequest(indexName).type(esType).source(mapping);
//创建索引
client.admin().indices().prepareCreate(indexName).execute().actionGet();
//为索引添加映射
PutMappingResponse indexresponse = client.admin().indices().putMapping(putmap).actionGet();
log.info("执行建立成功?" + indexresponse.isAcknowledged());
return indexresponse.isAcknowledged();
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
PutMappingRequest putMappingRequest = putMappingRequest(Strings.splitStringByCommaToArray(request.param("index")));
putMappingRequest.type(request.param("type"));
putMappingRequest.source(request.content().toUtf8());
putMappingRequest.updateAllTypes(request.paramAsBoolean("update_all_types", false));
putMappingRequest.reindex(request.paramAsBoolean("reindex", false));
putMappingRequest.timeout(request.paramAsTime("timeout", putMappingRequest.timeout()));
putMappingRequest.masterNodeTimeout(request.paramAsTime("master_timeout", putMappingRequest.masterNodeTimeout()));
putMappingRequest.indicesOptions(IndicesOptions.fromRequest(request, putMappingRequest.indicesOptions()));
client.admin().indices().putMapping(putMappingRequest, new AcknowledgedRestListener<PutMappingResponse>(channel));
}
public static PutMappingResponse putMapping(Client client, String indexName, IElasticSearchMapping mapping) {
try {
return internalPutMapping(client, indexName, mapping);
} catch(Exception e) {
if(log.isErrorEnabled()) {
log.error("Error Creating Index", e);
}
throw new PutMappingFailedException(indexName, e);
}
}
public static PutMappingResponse putMapping(Client client, String indexName, IElasticSearchMapping mapping) {
try {
return internalPutMapping(client, indexName, mapping);
} catch(Exception e) {
if(log.isErrorEnabled()) {
log.error("Error Creating Index", e);
}
throw new PutMappingFailedException(indexName, e);
}
}
/**
*
* @param indicesAdminClient
* @param indexName
* @param typeName
* @throws IOException
*/
private static void indexMapping(IndicesAdminClient indicesAdminClient, String indexName, String typeName) throws IOException {
//type就相当于表的
String typeSource=getIndexTypeSource(typeName,FIELD_NAME);
//typetwo
PutMappingRequest mapping = Requests.putMappingRequest(indexName).type(typeName).source("typeSource");
PutMappingResponse putMappingResponseTwo = indicesAdminClient.putMapping(mapping).actionGet();
}
/**
* This method applies the supplied mapping to the index.
*
* @param index The name of the index
* @param defaultMappings The default mappings
* @return true if the mapping was successful
*/
@SuppressWarnings("unchecked")
private boolean prepareMapping(String index, Map<String, Object> defaultMappings) {
boolean success = true;
for (Map.Entry<String, Object> stringObjectEntry : defaultMappings.entrySet()) {
Map<String, Object> mapping = (Map<String, Object>) stringObjectEntry.getValue();
if (mapping == null) {
throw new RuntimeException("type mapping not defined");
}
PutMappingRequestBuilder putMappingRequestBuilder = client.admin().indices().preparePutMapping()
.setIndices(index);
putMappingRequestBuilder.setType(stringObjectEntry.getKey());
putMappingRequestBuilder.setSource(mapping);
if (log.isLoggable(Level.FINE)) {
log.fine("Elasticsearch create mapping for index '"
+ index + " and type '" + stringObjectEntry.getKey() + "': " + mapping);
}
PutMappingResponse resp = putMappingRequestBuilder.execute().actionGet();
if (resp.isAcknowledged()) {
if (log.isLoggable(Level.FINE)) {
log.fine("Elasticsearch mapping for index '"
+ index + " and type '" + stringObjectEntry.getKey() + "' was acknowledged");
}
} else {
success = false;
log.warning("Elasticsearch mapping creation was not acknowledged for index '"
+ index + " and type '" + stringObjectEntry.getKey() + "'");
}
}
return success;
}
/**
* .
* @param response .
* @return .
*/
public static DcPutMappingResponse getInstance(PutMappingResponse response) {
if (response == null) {
return null;
}
return new DcPutMappingResponseImpl(response);
}
/**
* Mapping定義を更新する.
* @param index インデックス名
* @param type タイプ名
* @param mappings マッピング情報
* @return 非同期応答
*/
public ListenableActionFuture<PutMappingResponse> putMapping(String index,
String type,
Map<String, Object> mappings) {
PutMappingRequestBuilder builder = new PutMappingRequestBuilder(esTransportClient.admin().indices(), PutMappingAction.INSTANCE)
.setIndices(index)
.setType(type)
.setSource(mappings);
return builder.execute();
}
@Override
PutMappingResponse onParticularError(ElasticsearchException e) {
if (e instanceof IndexNotFoundException || e.getCause() instanceof IndexNotFoundException) {
throw new EsClientException.EsIndexMissingException(e);
}
if (e instanceof MapperParsingException) {
throw new EsClientException.EsSchemaMismatchException(e);
}
throw e;
}
/**
* .
* @param response .
* @return .
*/
public static DcPutMappingResponse getInstance(PutMappingResponse response) {
if (response == null) {
return null;
}
return new DcPutMappingResponseImpl(response);
}
/**
* Mapping定義を更新する.
* @param index インデックス名
* @param type タイプ名
* @param mappings マッピング情報
* @return 非同期応答
*/
public ListenableActionFuture<PutMappingResponse> putMapping(String index,
String type,
Map<String, Object> mappings) {
PutMappingRequestBuilder builder = new PutMappingRequestBuilder(esTransportClient.admin().indices())
.setIndices(index)
.setType(type)
.setSource(mappings);
return builder.execute();
}
@Override
PutMappingResponse onParticularError(ElasticsearchException e) {
if (e instanceof IndexMissingException || e.getCause() instanceof IndexMissingException) {
throw new EsClientException.EsIndexMissingException(e);
}
if (e instanceof MapperParsingException) {
throw new EsClientException.EsSchemaMismatchException(e);
}
throw e;
}
public void open() {
final IndicesExistsResponse existsResponse = client.admin().indices()
.prepareExists(index).execute().actionGet();
if (!existsResponse.isExists()) {
final CreateIndexResponse createIndexResponse = client.admin()
.indices().prepareCreate(index).execute().actionGet();
if (!createIndexResponse.isAcknowledged()) {
throw new TasteException("Failed to create " + index
+ " index.");
}
}
if (mappingBuilder != null) {
final GetMappingsResponse response = client.admin().indices()
.prepareGetMappings(index).setTypes(type).execute()
.actionGet();
if (response.mappings().isEmpty()) {
final PutMappingResponse putMappingResponse = client.admin()
.indices().preparePutMapping(index).setType(type)
.setSource(mappingBuilder).execute().actionGet();
if (!putMappingResponse.isAcknowledged()) {
throw new TasteException("Failed to create a mapping of"
+ index + "/" + type);
}
}
}
}
/**
* Setup ElasticSearch type mappings as a template that applies to all new indexes.
* Applies to all indexes that* start with our prefix.
*/
private void createMappings(final String indexName) {
//Added For Graphite Metrics
PutMappingResponse pitr = provider.getClient().admin().indices().preparePutMapping( indexName ).setType( "entity" ).setSource(
getMappingsContent() ).execute().actionGet();
if ( !pitr.isAcknowledged() ) {
throw new RuntimeException( "Unable to create default mappings" );
}
}
/**
* Setup ElasticSearch type mappings as a template that applies to all new indexes.
* Applies to all indexes that* start with our prefix.
*/
private void createMappings(final String indexName) throws IOException {
//Added For Graphite Metrics
Timer.Context timePutIndex = mappingTimer.time();
PutMappingResponse pitr = esProvider.getClient().admin().indices().preparePutMapping( indexName ).setType( "entity" ).setSource(
getMappingsContent() ).execute().actionGet();
timePutIndex.stop();
if ( !pitr.isAcknowledged() ) {
throw new IndexException( "Unable to create default mappings" );
}
}
@Override
protected XContentBuilder toXContent(PutMappingRequest request, PutMappingResponse response, XContentBuilder builder) throws IOException {
builder.startObject()
.field(Fields.OK, true)
.field(Fields.ACKNOWLEDGED, response.isAcknowledged());
builder.endObject();
return builder;
}
@Override
public ActionFuture<PutMappingResponse> putMapping(final PutMappingRequest request) {
return execute(PutMappingAction.INSTANCE, request);
}
@Override
public void putMapping(final PutMappingRequest request, final ActionListener<PutMappingResponse> listener) {
execute(PutMappingAction.INSTANCE, request, listener);
}
/**
* Adds a document map (mapping) to a specific index
*
* @param index
* - index name
* @param type
* - doucment type
* @param mapping
* - a JSON document represented as a string
*/
private static void addMappingToIndex(String indexName, String documentType, String mapping) {
PutMappingRequest putMappingRequest = new PutMappingRequest(indexName.toLowerCase());
putMappingRequest.source(mapping, XContentType.JSON).type(documentType.toLowerCase());
PutMappingResponse putMappingResponse;
try {
putMappingResponse = highLevelClient.indices().putMapping(putMappingRequest, getWriteHeaders());
if (putMappingResponse.isAcknowledged() == true) {
logger.info("Mapping for " + documentType + " in " + indexName + " was added successfully");
}
} catch (IOException e) {
logger.error(e);
}
}
public PutMappingResponse bulkPutMapping(String index, Configuration mapping) {
return client.admin().indices().preparePutMapping(index)
.setSource(mapping.underlying().root().
render(ConfigRenderOptions.concise())).execute().actionGet();
}
public PutMappingResponse putMapping(String index, String type,
Configuration mapping) {
return client.admin().indices().preparePutMapping(index).setType(type)
.setSource(mapping.underlying().root().
render(ConfigRenderOptions.concise())).execute().actionGet();
}
@Override
PutMappingResponse doProcess() {
return asyncPutMapping(mappings).actionGet();
}
@Override
public ListenableActionFuture<PutMappingResponse> putMapping(String index,
String type, Map<String, Object> mappings) {
throwException();
return super.putMapping(index, type, mappings);
}
@Override
public ListenableActionFuture<PutMappingResponse> putMapping(String index,
String type, Map<String, Object> mappings) {
throwException();
return super.putMapping(index, type, mappings);
}
@Override
public ListenableActionFuture<PutMappingResponse> putMapping(String index,
String type, Map<String, Object> mappings) {
throwException();
return super.putMapping(index, type, mappings);
}