java客户端的elasticSearch索引库的相关操作

时间:2024-01-03 21:22:38
package com.hope.es;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

import java.net.InetAddress;

/**
* 创建索引库
* @author newcityman
* @date 2020/1/16 - 18:24
*/
public class ElasticSearchClient {
@Test
public void createIndex() throws Exception{
//1、创建一个setting对象,相当于一个配置信息,主要配置集群的名称
Settings settings = Settings.builder()
.put("cluster.name", "my‐elasticsearch").build();
//2、创建一个客户端client对象
TransportClient client = new PreBuiltTransportClient(settings);
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9301));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9302));
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"),9303));
//3、使用client对象,创建一个索引库
client.admin().indices().prepareCreate("index_hello").get();
//4、关闭client对象
client.close();
}
/**
* 给索引库创建mappings
* @throws Exception
*/
@Test
public void setMapping() throws Exception {
//1、创建一个setting对象
Settings settings = Settings.builder().
put("cluster.name", "my‐elasticsearch").build();
//2、创建一个TransportClient对象,
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9301))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9302))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9303));
//3、创建一个Mappings信息
/* {
"article":{
"properties":{
"id":{
"type":"long",
"store":true
},
"title":{
"type":"text",
"store":true,
"analyzer":"ik_smart"
},
"content":{
"type":"text",
"store":true,
"analyzer":"ik_smart"
}
}
}
}*/
XContentBuilder builder= XContentFactory.jsonBuilder()
.startObject()
.startObject("article")
.startObject("properties")
.startObject("id")
.field("type","long")
.field("store",true)
.endObject()
.startObject("title")
.field("type","text")
.field("store",true)
.field("analyzer","ik_smart")
.endObject()
.startObject("content")
.field("type","text")
.field("store",true)
.field("analyzer","ik_smart")
.endObject()
.endObject()
.endObject()
.endObject();
//4、使用client向es服务器发送mapping信息
client.admin().indices()
//设置要做映射的索引
.preparePutMapping("index_hello")
//设置要做映射的type
.setType("article")
//mapping信息,可以使XContenxtBuilder对象,也可以使json格式的字符串
.setSource(builder)
//执行操作
.get();
//5、关闭client
client.close();
}
}