JAva操作単機版elasticseach

1970 ワード

package com.xicheng.es;

import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xichengxml
 * @date 2018/11/7
 * @description java     es
 */
public class OprateElasticsearch {

    private static final String HOST = "192.168.143.12";
    private static final int PORT = 9300;
    //        
    private static final String INDEXNAME = "es";
    //      
    private static final String TYPENAME = "xicheng";

    private static TransportClient client;

    public static void main(String[] args) throws Exception{
        client = getConnection();
        addData();
        client.close();
    }

    /**
     *   es
     * @return
     * @throws Exception
     */
    private static TransportClient getConnection() throws Exception{
        Settings settings = Settings.builder().build();
        TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddresses(new TransportAddress(InetAddress.getByName(HOST), PORT));
        System.out.println("    ");
        return client;
    }

    /**
     *       
     */
    private static void addData() {
        Map json = new HashMap();
        json.put("user","xichengxml");
        json.put("blog","https://www.jianshu.com/u/0666c519ec76");
        json.put("motoo","to be better me");
        IndexResponse response = client.prepareIndex(INDEXNAME, TYPENAME)
                .setSource(json)
                .get();
        System.out.println("    " + response.getResult());
    }
}