// 存放html文件的目录
public static String DATA_DIR = "F:\data";
public static Client client;
static {
Settings settings = Settings.settingsBuilder().put("cluster.name", "bd-es").build();
try {
client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("es"), 19301))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("es"), 19302))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("es"), 19303));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* admin():管理索引库的。client.admin().indices()
*
* 索引数据的管理:client.prepare
*
*/
@Test
public void createIndex() throws Exception {
IndicesExistsResponse resp = client.admin().indices().prepareExists("myindex").execute().actionGet();
if (resp.isExists()) {
client.admin().indices().prepareDelete("myindex").execute().actionGet();
}
client.admin().indices().prepareCreate("myindex").execute().actionGet();
new XContentFactory();
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("htmlbean")
.startObject("properties").startObject("title").field("type", "string").field("store", "yes")
.field("analyzer", "ik_max_word").field("search_analyzer", "ik_max_word").endObject()
.startObject("content").field("type", "string").field("store", "yes").field("analyzer", "ik_max_word")
.field("search_analyzer", "ik_max_word").endObject()
// .startObject("url").field("type", "string")
// .field("store", "yes").field("analyzer", "ik_max_word")
// .field("search_analyzer", "ik_max_word").endObject()
.endObject().endObject().endObject();
PutMappingRequest mapping = Requests.putMappingRequest("myindex").type("htmlbean").source(builder);
client.admin().indices().putMapping(mapping).actionGet();
}
改正两点后解决问题,
一处是用19301端口 而不是19201.19201端口只是HTTP端口。
第二处是"cluster.name", “bd-es” 要和config/elasticsearch.yml 配置的cluster.name一致。