- 1.连接集群。
//通过transport方式连接集群。(还可将java客户端作为node连接ES,数据丢失风险较高,只作测试集群用)
public static TransportClient getClient(String cluster_name) {
if (client != null) {
return client;
}
try {
//TransportClient类的可选配置:
//1:client.transport.sniff :默认FALSE true时,es会读取集群中的节点信息
//不需要在建立TransportClient对象时提供所有节点的网络地址;
//2:client.transport.ignore_cluster_name(默认false),ture时,ES会忽略
//配置中的集群名称并尝试连接到某个可能连接的集群上。危险!!!!
//3:client.transport.ping.timeout(默认5s)
//4:client。transport.nodes_sampler_interval(默认5s)检查节点可用性间隔时间。
Settings settings = Settings.builder().put("cluster.name", cluster_name)
.put("client.transport.sniff", true).build();
client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hostname"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
- 2.创建、删除索引。
//不带参数创建index
private static Boolean createIndex(TransportClient client, String index_name) {
try {
boolean bool = client.admin().indices().prepareCreate(index_name).execute
().actionGet().isAcknowledged();
return bool;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// 带参数创建index
private static Boolean createIndex(TransportClient client, String index_name, int
number_of_shards, int number_of_replicas) {
try {
Settings indexSettings = Settings.builder()
.put("number_of_shards", number_of_shards) //添加分片数
.put("number_of_replicas", number_of_replicas) //添加副本数
.build();
CreateIndexRequest indexRequest = new CreateIndexRequest(index_name, indexSettings);
boolean bool = client.admin().indices().create(indexRequest).actionGet
().isAcknowledged();
return bool;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//删除索引
private static Boolean deleteIndex(TransportClient client, String index_name) {
try {
boolean bool = client.admin().indices().prepareDelete(index_name).execute
().actionGet().isAcknowledged();
return bool;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
//查询索引是否存在
public static Boolean hasIndex(String indexName) {
try {
boolean ishas = client.admin().indices().prepareExists(indexName).execute
().actionGet().isExists();
return ishas;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
3.建立mapping
/** 类型分类:
* string字段 、数字类型、日期类型、复合类型、地理类型(geo_point,geo_shape)、专用类型(ipv4、completion、token_count、mapper-murmur3)多值字段、
* @param client
*/
public static Boolean createMapping(TransportClient client, String index_name, String type_name) {
try {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().startObject("properties")
.startObject("name").field("type", "string").field("store", "yes").endObject()
.startObject("weight").field("type", "float").field("store", "yes").endObject()
.startObject("price").field("type", "double").field("store", "yes").endObject()
.startObject("Date_of_storage").field("type", "date").field("store", "yes").endObject()
.startObject("function").field("type", "string").field("analyzer", "ik_max_word").endObject()
.endObject().endObject();
PutMappingRequest mapping = Requests.putMappingRequest(index_name).type(type_name).source(builder);
client.admin().indices().putMapping(mapping).actionGet();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
- 4.增
/**
* 单条信息索引,有ID,通过map传递。不传ID时ES将自动分配ID 有ID 存在map中以"_id"字段保存
*
* @param client
* @param index_name
* @param type_name
* @param map
* @return true or false
*/
private static Boolean index_doc(TransportClient client, String index_name, String type_name, HashMap<String, Object> map) {
//IndexRequestBuilder对象的常用操作:
//1:setSource()添加文档源
//2:setIndex,setType,setID 同样可以在prepareindex里带参设置
//3:setRouting ,setParent 同GET方法一样
//4:setOpType()参数有“index",“create”两种,默认为index,当文档ID已经在索引之中时,文档被覆盖。
// 当使用create参数时,索引操作将失败。
//5:setVersion:设置版本号,若指定版本不存在,更新失败。改方法确保在读取和更新文当期间文档未被修改。
IndexResponse response = null;
try {
if (null != map.get("_id")) {
String ID = map.remove("_id").toString();
map.remove("_id");
response = client.prepareIndex(index_name, type_name, ID).setSource(map).get();
} else {
response = client.prepareIndex(index_name, type_name).setSource(map).get();
}
if (response.getVersion() > 0) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
//IndexResponse 对象常用操作:
//1:getIndex(),getTpye(),getId(),getVersion().
//2:getMatches():返回匹配被索引文档的过滤器查询列表。
}
/**
* 批量索引数据 有ID时以"_id”字段传值到map当中
*
* @param client
* @param index_name
* @param type_name
* @param list
* @return true or false
*/
private static Boolean add_docs(TransportClient client, String index_name, String type_name, List<Map> list) {
Boolean boo = true;
int count = 0;
try {
if (list.isEmpty()) {
log.error("插入数据为空集合!!!!");
} else {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (Map map : list) {
try {
Object ID = map.get("_id");
if (null == ID) {
bulkRequest.add(client.prepareIndex(index_name, type_name).setSource(map));
} else {
map.remove("_id");
bulkRequest.add(client.prepareIndex(index_name, type_name, ID.toString()).setSource(map));
}
count++;
//每一千条导一次,根据自己节点数,分片数决定。
if (count % 1000 == 0) {
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
bulkRequest = client.prepareBulk();
if (bulkResponse.hasFailures()) { //判断是否有导入失败的文档
boo = false;
}
} else if (count == list.size()) {
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) { //判断是否有导入失败的文档
boo = false;
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
return boo;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
log.info("添加对象列表:" + (boo ? " 成功!" : " 失败"));
}
}
}
- 5.删
/**
* 根据ID 删除文档
*
* @param client
* @param index_name
* @param type_name
* @param ID
* @return
*/
private static Boolean del_byID(TransportClient client, String index_name, String type_name, String ID) {
try {
//DeleteRequestBuilder实例可追加参数:
//1:setVersion(long)指定删除的版本号。
DeleteResponse response = client.prepareDelete(index_name, type_name, ID)
.execute().actionGet();
System.out.println(response.status());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
- 6.查
/**
* 根据ID单条检索数据
*
* @param client
* @param index_name
* @param type_name
* @param ID
*/
private static void getdoc_ByID(TransportClient client, String index_name, String type_name, String ID) {
//GetRequestBuilder实例可附加信息:
//1:setIndex(string) setType(string) setId(string):添加位置信息
//2:setRouting(string)设定路由值,确定将用哪个分片来执行请求
//3:.setParent(string)设定文档的父文档ID。
//4:setPreference(string)设置查询偏好。
//5:setRefresh(boolean):是否需要在操作前执行刷新。默认false
//6:setRealtime(boolean):指定get操作是否实时。默认ture。
GetResponse response = client.prepareGet(index_name, type_name, ID)
.execute().actionGet();
//Get操作响应,GetResponse对象的常用方法:
//1:isExists():文档存在?
//2:getIndex(),getType(),getId(),getVersion();
//3:isSourceEmpty():文档源是否可用或者不包含在当前的返回文档中。
//4:getSourceXXX()按指定格式读取文档。
//5:getField(string):返回便是文档字段的对象。
System.out.println(response);
System.out.println(response.getSource().get("doc"));
}
- 7.改
/**
* 根据ID更新数据。(目前es更新操作只支持单条数据更新,因为更新是要检索+对比+合并+覆盖)
*
* @param client
* @param index_name
* @param type_name
* @param ID
* @param map
* @return true or false
*/
private static Boolean update_byID(TransportClient client, String index_name, String type_name, String ID, HashMap<String, Object> map) {
try {
//1:UpdateRequestBuilder对象可追加参数:
//2:setScript(string):设置修改脚本。
//3:setRetryOnConflict(int) 默认为0:发现读取版本与更新版本不一致时重新操作次数。
//4:setDoc()设置跟新文档片段。如果设置了script,则文档将被忽略。
//5:setUpsert() 如果文档不存在,它会被重新索引。如果存在,则更新。
//6:setDocAsUpsert(boo):如果文档不存在,setdoc会将文档加入到索引中。默认false.
UpdateResponse response = client.prepareUpdate(index_name, type_name, ID)
//.setDocAsUpsert(true)
.setDoc(map)
.execute().actionGet();
System.out.println(response.status());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}