下面是一个基本的 Java 代码示例,来连接 Elasticsearch 并插入数据:

import org.elasticsearch.action.index.IndexResponse;
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.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import java.net.InetAddress;

public class ElasticsearchExample {

    public static void main(String[] args) throws Exception {

        // 设置集群名称
        Settings settings = Settings.settingsBuilder().put('cluster.name', 'myCluster').build();

        // 创建 client
        Client client = TransportClient.builder().settings(settings).build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName('localhost'), 9300));

        // 创建 json 数据
        XContentBuilder builder = XContentFactory.jsonBuilder().startObject()
                .field('name', 'John')
                .field('age', 25)
                .field('email', 'john@example.com')
                .endObject();

        // 插入数据
        IndexResponse response = client.prepareIndex('myindex', 'mytype')
                .setSource(builder)
                .get();

        // 输出响应结果
        System.out.println('插入数据成功,响应结果为:' + response.toString());

        // 关闭 client
        client.close();
    }
}

在这个示例中,我们首先设置了集群名称并创建了一个客户端。然后,我们使用 XContentFactory 创建了一个 JSON 数据对象,并插入到名为 'myindex' 的索引和名为 'mytype' 的类型中。最后,我们输出了响应结果并关闭了客户端。

Java 连接 Elasticsearch 插入数据 - 示例代码

原文地址: https://www.cveoy.top/t/topic/oNlZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录