Elasticsearch--java API(更新操作)亲测


ClientHelper.java

package es;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.plugin.deletebyquery.DeleteByQueryPlugin;
import org.elasticsearch.shield.ShieldPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.bind.annotation.InitBinder;

/**
 * Es服务器初始化类
 * @author Administrator
 *
 */
public class ClientHelper {
   
    //log4j
    private static Logger logger = LoggerFactory.getLogger(ClientHelper.class);
    
    //存放es集群名称以及嗅探设置
    private Settings setting;
    
    //es客户端存放集合
    private Map<String, Client> clientMap = new ConcurrentHashMap<String, Client>();
    
    //ip端口号集合
    private Map<String, Integer> ips = new HashMap<String, Integer>();
    
    //默认集群名称
    private String clusterName = "elasticsearch";
    
    public ClientHelper(){
        init();
    }
    
    
    private static class ClientHolder{
        private static final ClientHelper INSTANCE = new ClientHelper();
    }
    public static final ClientHelper getInstance(){
        return ClientHolder.INSTANCE;
    }
    
     /**
     * 得到客户端连接
     * @return
     */
    public Client getClient() {
        return getClient(clusterName);
    }
    /**
     * 得到客户端连接
     * @return
     */
    public Client getClient(String clusterName) {
        Client c = clientMap.get(clusterName);
        return c;
    }
    
    /**
     * 初始化EsClient
     */
    public void init(){
        Resource resource = new ClassPathResource("config/config.properties");
        try {
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            String host = properties.getProperty("host");
            String port = properties.getProperty("port");
            clusterName = properties.getProperty("clusterName");
            String [] hosts = host.split(";");
            String [] ports = port.split(";");
            for(int i=0;i< hosts.length;i++){
                int portNo = Integer.valueOf(ports[i].trim());
                ips.put(hosts[i].trim(), portNo);
            }
            
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        setting = Settings.settingsBuilder()
                .put("client.transport.sniff",true)
                .put("cluster.name",clusterName)
               .build();
         addClient(setting, getAllAddress(ips));
    }
    
     /**
     * 查询所有ES服务器地址
     *
     * @return
     */
    public List<InetSocketTransportAddress> getAllAddress(Map<String, Integer>ips){
         List<InetSocketTransportAddress> addressList = new ArrayList<InetSocketTransportAddress>();
         for(String ip:ips.keySet()){
             try {
                addressList.add(new InetSocketTransportAddress(InetAddress.getByName(ip),ips.get(ip)));
            } catch (UnknownHostException e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
         }
         return addressList;
    }
    
    /**
     * 往集群中增加ES服务器
     * @param setting   设置
     * @param transportAddress   传输地址
     */
    public void addClient(Settings setting, List<InetSocketTransportAddress> transportAddress) {
          Client client = new TransportClient.Builder().addPlugin(ShieldPlugin.class).addPlugin(DeleteByQueryPlugin.class).settings(setting).build()
                    .addTransportAddresses(transportAddress
                            .toArray(new InetSocketTransportAddress[transportAddress.size()]));
            clientMap.put(setting.get("cluster.name"), client);
        
    }
}

 

updateRecord.java

package es;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import com.alibaba.fastjson.JSON;

public class updateRecord {

    public String updateRecord(String index, String type, String id, Map<String, Object> newContent) {
        
        ClientHelper clientHelper = new ClientHelper();
        Client client = clientHelper.getClient();
        XContentBuilder xBuild = null;
        Map<String, Object> returnMsg = new HashMap<String, Object>();
        try {
            xBuild = XContentFactory.jsonBuilder().startObject();
            for (String key : newContent.keySet()) {
                xBuild.field(key, newContent.get(key));
            }
            xBuild.endObject();
        } catch (IOException e) {
            e.printStackTrace();
            returnMsg.put("errorMsg", e.getMessage());
        }
        UpdateResponse response = client.prepareUpdate(index, type, id).setDoc(xBuild).execute().actionGet();
        Integer success = response.getShardInfo().getSuccessful();
        boolean result = success > 0 ? true : false;
        returnMsg.put("success", result);
        return JSON.toJSONString(returnMsg);
        
    }
}

测试test

/**
     * 测试更新
     */
    @Test
    public static void update(){
        
        updateRecord record = new updateRecord();
        String index = "es_test4";
        String type = "book";
        String id = "8276e3679d4b4fca94ed806092a373c0";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("number", 80);
        map.put("price", 58.92);
        map.put("name", "狼图腾");
        map.put("publish_data", new Date());
        map.put("id", "11111111111");
        map.put("title", "励志故事");
        String msg = record.updateRecord(index, type, id, map);
        System.out.println(msg);
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM