Java Code Examples for org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse#isAcknowledged()

The following examples show how to use org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse#isAcknowledged() . 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: MappingUpdatedAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 2
Source File: ElasticsearchUtil.java    From SpringBootLearn with Apache License 2.0 5 votes vote down vote up
/**
 * 创建索引以及映射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();
}
 
Example 3
Source File: ElasticsearchClient.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 4
Source File: AbstractWriter.java    From elasticsearch-taste with Apache License 2.0 5 votes vote down vote up
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);
            }
        }
    }
}
 
Example 5
Source File: EsIndexMappingMigrationPlugin.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * 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" );
    }
}
 
Example 6
Source File: EsEntityIndexImpl.java    From usergrid with Apache License 2.0 5 votes vote down vote up
/**
 * 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" );
    }
}
 
Example 7
Source File: Indexer.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * 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);
	}
}
 
Example 8
Source File: ItemRequestHandler.java    From elasticsearch-taste with Apache License 2.0 4 votes vote down vote up
private void doItemMappingCreation(final Params params,
        final RequestHandler.OnErrorListener listener,
        final Map<String, Object> requestMap,
        final Map<String, Object> paramMap, final RequestHandlerChain chain) {
    final String index = params.param(
            TasteConstants.REQUEST_PARAM_ITEM_INDEX, params.param("index"));
    final String type = params.param(
            TasteConstants.REQUEST_PARAM_ITEM_TYPE,
            TasteConstants.ITEM_TYPE);
    final String itemIdField = params.param(
            TasteConstants.REQUEST_PARAM_ITEM_ID_FIELD,
            TasteConstants.ITEM_ID_FIELD);
    final String timestampField = params.param(
            TasteConstants.REQUEST_PARAM_TIMESTAMP_FIELD,
            TasteConstants.TIMESTAMP_FIELD);

    try (XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()) {
        final ClusterHealthResponse healthResponse = client
                .admin()
                .cluster()
                .prepareHealth(index)
                .setWaitForYellowStatus()
                .setTimeout(
                        params.param("timeout",
                                DEFAULT_HEALTH_REQUEST_TIMEOUT)).execute()
                .actionGet();
        if (healthResponse.isTimedOut()) {
            listener.onError(new OperationFailedException(
                    "Failed to create index: " + index + "/" + type));
        }

        final XContentBuilder builder = jsonBuilder//
                .startObject()//
                .startObject(type)//
                .startObject("properties")//

                // @timestamp
                .startObject(timestampField)//
                .field("type", "date")//
                .field("format", "date_optional_time")//
                .endObject()//

                // item_id
                .startObject(itemIdField)//
                .field("type", "long")//
                .endObject()//

                // system_id
                .startObject("system_id")//
                .field("type", "string")//
                .field("index", "not_analyzed")//
                .endObject()//

                .endObject()//
                .endObject()//
                .endObject();

        final PutMappingResponse mappingResponse = client.admin().indices()
                .preparePutMapping(index).setType(type).setSource(builder)
                .execute().actionGet();
        if (mappingResponse.isAcknowledged()) {
            fork(() -> execute(params, listener, requestMap, paramMap,
                    chain));
        } else {
            listener.onError(new OperationFailedException(
                    "Failed to create mapping for " + index + "/" + type));
        }
    } catch (final Exception e) {
        listener.onError(e);
    }
}
 
Example 9
Source File: PreferenceRequestHandler.java    From elasticsearch-taste with Apache License 2.0 4 votes vote down vote up
private void doPreferenceMappingCreation(final Params params,
        final RequestHandler.OnErrorListener listener,
        final Map<String, Object> requestMap,
        final Map<String, Object> paramMap, final RequestHandlerChain chain) {
    final String index = params.param("index");
    final String type = params
            .param("type", TasteConstants.PREFERENCE_TYPE);
    final String userIdField = params.param(
            TasteConstants.REQUEST_PARAM_USER_ID_FIELD,
            TasteConstants.USER_ID_FIELD);
    final String itemIdField = params.param(
            TasteConstants.REQUEST_PARAM_ITEM_ID_FIELD,
            TasteConstants.ITEM_ID_FIELD);
    final String valueField = params.param(
            TasteConstants.REQUEST_PARAM_VALUE_FIELD,
            TasteConstants.VALUE_FIELD);
    final String timestampField = params.param(
            TasteConstants.REQUEST_PARAM_TIMESTAMP_FIELD,
            TasteConstants.TIMESTAMP_FIELD);

    try (XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()) {
        final ClusterHealthResponse healthResponse = client
                .admin()
                .cluster()
                .prepareHealth(index)
                .setWaitForYellowStatus()
                .setTimeout(
                        params.param("timeout",
                                DEFAULT_HEALTH_REQUEST_TIMEOUT)).execute()
                .actionGet();
        if (healthResponse.isTimedOut()) {
            listener.onError(new OperationFailedException(
                    "Failed to create index: " + index + "/" + type));
        }

        final XContentBuilder builder = jsonBuilder//
                .startObject()//
                .startObject(type)//
                .startObject("properties")//

                // @timestamp
                .startObject(timestampField)//
                .field("type", "date")//
                .field("format", "date_optional_time")//
                .endObject()//

                // user_id
                .startObject(userIdField)//
                .field("type", "long")//
                .endObject()//

                // item_id
                .startObject(itemIdField)//
                .field("type", "long")//
                .endObject()//

                // value
                .startObject(valueField)//
                .field("type", "double")//
                .endObject()//

                .endObject()//
                .endObject()//
                .endObject();

        final PutMappingResponse mappingResponse = client.admin().indices()
                .preparePutMapping(index).setType(type).setSource(builder)
                .execute().actionGet();
        if (mappingResponse.isAcknowledged()) {
            fork(() -> execute(params, listener, requestMap, paramMap,
                    chain));
        } else {
            listener.onError(new OperationFailedException(
                    "Failed to create mapping for " + index + "/" + type));
        }
    } catch (final Exception e) {
        listener.onError(e);
    }
}
 
Example 10
Source File: UserRequestHandler.java    From elasticsearch-taste with Apache License 2.0 4 votes vote down vote up
private void doUserMappingCreation(final Params params,
        final RequestHandler.OnErrorListener listener,
        final Map<String, Object> requestMap,
        final Map<String, Object> paramMap, final RequestHandlerChain chain) {
    final String index = params.param(
            TasteConstants.REQUEST_PARAM_USER_INDEX, params.param("index"));
    final String type = params.param(
            TasteConstants.REQUEST_PARAM_USER_TYPE,
            TasteConstants.USER_TYPE);
    final String userIdField = params.param(
            TasteConstants.REQUEST_PARAM_USER_ID_FIELD,
            TasteConstants.USER_ID_FIELD);
    final String timestampField = params.param(
            TasteConstants.REQUEST_PARAM_TIMESTAMP_FIELD,
            TasteConstants.TIMESTAMP_FIELD);

    try (XContentBuilder jsonBuilder = XContentFactory.jsonBuilder()) {
        final ClusterHealthResponse healthResponse = client
                .admin()
                .cluster()
                .prepareHealth(index)
                .setWaitForYellowStatus()
                .setTimeout(
                        params.param("timeout",
                                DEFAULT_HEALTH_REQUEST_TIMEOUT)).execute()
                .actionGet();
        if (healthResponse.isTimedOut()) {
            listener.onError(new OperationFailedException(
                    "Failed to create index: " + index + "/" + type));
        }

        final XContentBuilder builder = jsonBuilder//
                .startObject()//
                .startObject(type)//
                .startObject("properties")//

                // @timestamp
                .startObject(timestampField)//
                .field("type", "date")//
                .field("format", "date_optional_time")//
                .endObject()//

                // user_id
                .startObject(userIdField)//
                .field("type", "long")//
                .endObject()//

                // system_id
                .startObject("system_id")//
                .field("type", "string")//
                .field("index", "not_analyzed")//
                .endObject()//

                .endObject()//
                .endObject()//
                .endObject();

        final PutMappingResponse mappingResponse = client.admin().indices()
                .preparePutMapping(index).setType(type).setSource(builder)
                .execute().actionGet();
        if (mappingResponse.isAcknowledged()) {
            fork(() -> execute(params, listener, requestMap, paramMap,
                    chain));
        } else {
            listener.onError(new OperationFailedException(
                    "Failed to create mapping for " + index + "/" + type));
        }
    } catch (final Exception e) {
        listener.onError(e);
    }
}
 
Example 11
Source File: ElasticsearchDataModelTest.java    From elasticsearch-taste with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {
    clusterName = "es-taste-" + System.currentTimeMillis();
    runner = new ElasticsearchClusterRunner();
    runner.onBuild(new ElasticsearchClusterRunner.Builder() {
        @Override
        public void build(final int number, final Builder settingsBuilder) {
            settingsBuilder.put("http.cors.enabled", true);
            settingsBuilder.put("http.cors.allow-origin", "*");
            settingsBuilder.put("index.number_of_shards", 3);
            settingsBuilder.put("index.number_of_replicas", 0);
            settingsBuilder.putArray("discovery.zen.ping.unicast.hosts", "localhost:9301-9310");
            settingsBuilder.put("plugin.types",
                    "org.codelibs.elasticsearch.taste.TastePlugin");
            settingsBuilder.put("index.unassigned.node_left.delayed_timeout", "0");
        }
    }).build(newConfigs().clusterName(clusterName).numOfNode(numOfNode));

    runner.ensureYellow();
    Client client = runner.client();

    // Wait for Yellow status
    client.admin().cluster().prepareHealth().setWaitForYellowStatus()
            .setTimeout(TimeValue.timeValueMinutes(1)).execute()
            .actionGet();

    final CreateIndexResponse response = client.admin().indices()
            .prepareCreate(TEST_INDEX).execute().actionGet();
    if (!response.isAcknowledged()) {
        throw new TasteException("Failed to create index: " + TEST_INDEX);
    }

    final XContentBuilder userBuilder = XContentFactory.jsonBuilder()//
            .startObject()//
            .startObject(TasteConstants.USER_TYPE)//
            .startObject("properties")//

            // @timestamp
            .startObject(TasteConstants.TIMESTAMP_FIELD)//
            .field("type", "date")//
            .field("format", "date_optional_time")//
            .endObject()//

            // user_id
            .startObject(TasteConstants.USER_ID_FIELD)//
            .field("type", "long")//
            .endObject()//

            // id
            .startObject("id")//
            .field("type", "string")//
            .field("index", "not_analyzed")//
            .endObject()//

            .endObject()//
            .endObject()//
            .endObject();

    final PutMappingResponse userResponse = client.admin().indices()
            .preparePutMapping(TEST_INDEX)
            .setType(TasteConstants.USER_TYPE).setSource(userBuilder)
            .execute().actionGet();
    if (!userResponse.isAcknowledged()) {
        throw new TasteException("Failed to create user mapping.");
    }

    final XContentBuilder itemBuilder = XContentFactory.jsonBuilder()//
            .startObject()//
            .startObject(TasteConstants.ITEM_TYPE)//
            .startObject("properties")//

            // @timestamp
            .startObject(TasteConstants.TIMESTAMP_FIELD)//
            .field("type", "date")//
            .field("format", "date_optional_time")//
            .endObject()//

            // item_id
            .startObject(TasteConstants.ITEM_ID_FIELD)//
            .field("type", "long")//
            .endObject()//

            // id
            .startObject("id")//
            .field("type", "string")//
            .field("index", "not_analyzed")//
            .endObject()//

            .endObject()//
            .endObject()//
            .endObject();

    final PutMappingResponse itemResponse = client.admin().indices()
            .preparePutMapping(TEST_INDEX)
            .setType(TasteConstants.ITEM_TYPE).setSource(itemBuilder)
            .execute().actionGet();
    if (!itemResponse.isAcknowledged()) {
        throw new TasteException("Failed to create item mapping.");
    }
}
 
Example 12
Source File: S3River.java    From es-amazon-s3-river with Apache License 2.0 4 votes vote down vote up
private void pushMapping(String index, String type, XContentBuilder xcontent) throws Exception {
   if (logger.isTraceEnabled()){
      logger.trace("pushMapping(" + index + ", " + type + ")");
   }

   // If type does not exist, we create it
   boolean mappingExist = isMappingExist(index, type);
   if (!mappingExist) {
      logger.debug("Mapping [" + index + "]/[" + type + "] doesn't exist. Creating it.");

      // Read the mapping json file if exists and use it.
      if (xcontent != null){
         if (logger.isTraceEnabled()){
            logger.trace("Mapping for [" + index + "]/[" + type + "]=" + xcontent.string());
         }
         // Create type and mapping
         PutMappingResponse response = client.admin().indices()
               .preparePutMapping(index)
               .setType(type)
               .setSource(xcontent)
               .execute().actionGet();       
         if (!response.isAcknowledged()){
            throw new Exception("Could not define mapping for type [" + index + "]/[" + type + "].");
         } else {
            if (logger.isDebugEnabled()){
               if (mappingExist){
                  logger.debug("Mapping definition for [" + index + "]/[" + type + "] succesfully merged.");
               } else {
                  logger.debug("Mapping definition for [" + index + "]/[" + type + "] succesfully created.");
               }
            }
         }
      } else {
         if (logger.isDebugEnabled()){
            logger.debug("No mapping definition for [" + index + "]/[" + type + "]. Ignoring.");
         }
      }
   } else {
      if (logger.isDebugEnabled()){
         logger.debug("Mapping [" + index + "]/[" + type + "] already exists and mergeMapping is not set.");
      }
   }
   if (logger.isTraceEnabled()){
      logger.trace("/pushMapping(" + index + ", " + type + ")");
   }
}
 
Example 13
Source File: ESClient.java    From uavstack with Apache License 2.0 3 votes vote down vote up
/**
 * setIndexTypeMapping require Index Creation first
 * 
 * @param index
 * @param type
 * @param properties
 * @return
 * @throws IOException
 */
public boolean setIndexTypeMapping(String index, String type, Map<String, Map<String, Object>> properties)
        throws IOException {

    PutMappingRequest pmp = Requests.putMappingRequest(index).type(type).source(createMapping(type, properties));
    PutMappingResponse resp = client.admin().indices().putMapping(pmp).actionGet();

    return resp.isAcknowledged();

}