解决ElasticsSearch利用Java连接的问题

此链接中异常问题解决办法:
https://blog.csdn.net/baidu_26773887/article/details/82856567
1.导入依赖

<!--ElasticSearch++++++++++++-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>

2.在pom.xml中写入,防止版本号引起错误

<properties>
         <elasticsearch.version>5.2.0</elasticsearch.version>
    </properties>

3.如果出现netty问题,则导入下面依赖(无错误不导入)

<dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.13.Final</version>
        </dependency>

4.开发代码
4.1 往索引插入数据

 Settings settings = Settings.builder().put("cluster.name", "my-application").build();//my-application是集群名称,可以写多个
            TransportClient client = new PreBuiltTransportClient(settings);
            client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("192.168.0.118"),9300));//ip地址是虚拟机的centos的ip,9300为tcp的端口号,不是访问elasticssearch的http端口号9200
            BulkRequestBuilder bulkRequest = client.prepareBulk();
    
            try {
            //参数依次是 索引 类型 id
            //字段  内容(对应所创建的数据库)
                IndexResponse response = client.prepareIndex("jtthink", "news", "907")
                        .setSource(jsonBuilder()
                                .startObject()
                                .field("title", "test2")
                                .field("content", "test2")
                                .field("tags", "tags")
                                .endObject()
                        )
                        .get();
            } catch (IOException e) {
                e.printStackTrace();
            }

4.2获取数据

GetResponse getResponse = client.prepareGet("jtthink", "news", "901").get();
        //System.out.println(getResponse.getSourceAsString());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值