1.根据id获取一条数据
2.获取es索引结构
3.修改数据
package com.yb.es;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.NoNodeAvailableException;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import com.alibaba.fastjson.JSONObject;
public class GetData {
String esTable="land_chufa";
public static void main(String[] args) {
//根据id获取一条数据
new GetData().getDataById();
//获取表结构
// new GetData().getESTable();
}
private void getESTable() {
Client client = ESUtils.getClient();
ImmutableOpenMap<String, MappingMetaData> mappings = client.admin().cluster().prepareState().execute().actionGet().getState().getMetaData().getIndices().get(esTable).getMappings();
String mapping = mappings.get(esTable).source().toString();
System.out.println(mapping);
}
private void getDataById() {
String esid="AWsMss1CUgsUu1M-MHuY";
Client client = ESUtils.getClient();
GetResponse response = client.prepareGet(esTable,esTable,esid).get();
String str = response.getSourceAsString();
System.out.println(str);
//根据主键修改数据
toUpdate(esid,str);
}
private void toUpdate(String esid, String str) {
Client client = ESUtils.getClient();
JSONObject jsonObject = JSONObject.parseObject(str);
jsonObject.put("pname", "定海区临城街道惠民桥村村民哈哈哈");
while(true) {
try {
UpdateRequestBuilder updateBuilder = client.prepareUpdate(esTable, esTable, esid);
updateBuilder.setDoc(jsonObject.toString()).execute().actionGet();//setRefresh(true)实时刷新
System.out.println("修改成功");
break;
} catch (NoNodeAvailableException e) {
try {
System.out.println("节点连不上,重试 sleep10s");
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
}
}
修改成功