Elasticsearch java api 插入数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zgahlibin/article/details/78436616

首先java依赖的jar包要与es服务端的版本对应

这里是es5.5.1的版本。

Elasticsearch5.5.1  java api 创建客户端,插入数据。

需要注意的是要在客户端上创建index,type和mapping。在命令行模式没有type mapping也是可以插入数据的,这点不同。



package com.jiayun.core.elasticsearch.utils;



import java.net.InetAddress;
import java.net.UnknownHostException;


import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;


import com.alibaba.fastjson.JSONObject;


public class ES551Client {



@SuppressWarnings({ "resource", "unused" })
public static void main(String[] args) throws UnknownHostException {
//client
  // 设置集群名称
    Settings settings = Settings.builder().put("cluster.name", "my-application").build();
    // 创建client
TransportClient client = new PreBuiltTransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("120.77.151.154"), 9300));



JSONObject json = new JSONObject();
json.put("user", "小明");
json.put("title", "Java Engineer");
json.put("desc", "web 开发");
IndexResponse response = client.prepareIndex("accounts", "person")
        .setSource(json, XContentType.JSON)
        .get();

String _index = response.getIndex();
System.out.println(_index);
}


}

猜你喜欢

转载自blog.csdn.net/zgahlibin/article/details/78436616