java操作单机版elasticseach

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());
    }
}

你可能感兴趣的:(java操作单机版elasticseach)