ElasticSearch入门- 设置分片副本数量及putMapping
Settings settings = ImmutableSettings.settingsBuilder()//5个主分片 .put("number_of_shards", 5) //测试环境,减少副本提高速度 .put("number_of_replicas", 0).build();
?在非生产环境,这个副本最好设置成0,即不保留副本,因为每增加一个副本,写数据的成本就增加一倍。本来elasticsearch写的速度就比较慢。
?
2、如果在创建Index时,顺便把type的mapping也创建?
//首先创建索引库CreateIndexResponse indexresponse = client.admin().indices()//这个索引库的名称还必须不包含大写字母.prepareCreate("testindex").setSettings(settings)//这里直接添加type的mapping.addMapping("testType", getMapping())
?有几个type就addMapping几个。
综合起来的代码:
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;import org.elasticsearch.client.Client;import org.elasticsearch.common.settings.ImmutableSettings;import org.elasticsearch.common.settings.Settings;import org.elasticsearch.common.xcontent.XContentBuilder;import com.donlianli.es.ESUtils;/** * 创建索引时,指定分片及副本 * 并且创建type一起执行 * @author donlianli@126.com */public class PutMappingTest {public static void main(String[] argv) throws Exception{Client client = ESUtils.getClient();Settings settings = ImmutableSettings.settingsBuilder()//5个主分片 .put("number_of_shards", 5) //测试环境,减少副本提高速度 .put("number_of_replicas", 0).build();//首先创建索引库CreateIndexResponse indexresponse = client.admin().indices()//这个索引库的名称还必须不包含大写字母.prepareCreate("testindex").setSettings(settings)//这里直接添加type的mapping.addMapping("testType", getMapping()).execute().actionGet();System.out.println(indexresponse.acknowledged());}/** * mapping 一旦定义,之后就不能修改。 * @return * @throws Exception */private static XContentBuilder getMapping() throws Exception{XContentBuilder mapping = jsonBuilder() .startObject() .startObject("test") .startObject("properties") .startObject("id") .field("type", "long") .field("store", "yes") .endObject() .startObject("type") .field("type", "string") .field("index", "not_analyzed") .endObject() .startObject("catIds") .field("type", "integer") .endObject() .endObject() .endObject() .endObject(); return mapping;}}
?3、如果修改副本的数量?
import org.elasticsearch.action.admin.indices.settings.UpdateSettingsResponse;import org.elasticsearch.client.Client;import org.elasticsearch.common.settings.ImmutableSettings;import org.elasticsearch.common.settings.Settings;import com.donlianli.es.ESUtils;/** * 更新副本个数 * @author donlianli@126.com */public class UpdateReplicaTest {public static void main(String[] argv) throws Exception{Client client = ESUtils.getClient();Settings settings = ImmutableSettings.settingsBuilder() //可以更新的配置还有很多,见elasticsearch官网 .put("number_of_replicas", 2).build();//首先创建索引库UpdateSettingsResponse updateSettingsResponse = client.admin().indices().prepareUpdateSettings("testindex").setSettings(settings).execute().actionGet();System.out.println(updateSettingsResponse);}}
?
?
?
?
对这类话题感兴趣?欢迎发送邮件至donlianli@126.com关于我:邯郸人,擅长Java,Javascript,Extjs,oracle sql。更多我之前的文章,可以访问?我的空间