您的位置:首页 > 编程语言 > Java开发

Elasticsearch java api 插入数据

2017-11-03 16:08 357 查看
首先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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: