Java操作es的问题与案例 demo

Java操作es的问题与案例 demo

问题1:No Log4j 2 configuration file found

ERROR StatusLogger No Log4j 2 configuration file found.
 Using default configuration (logging only errors to the console), or user programmatically provided configurations.
  Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. 
  See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2

根据提示很简答,需要加log4j-core日志工具包,不过需要多一个,maven添加如下依赖

使用Log4j 2

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.1</version>
</dependency>

最好在src/main/resources 目录加入log4j2.properties,例如:

appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout

rootLogger.level = info
rootLogger.appenderRef.console.ref = console

参考文章:https://blog.csdn.net/HuoqilinHeiqiji/article/details/87776853

问题2

Exception in thread "main" NoNodeAvailableException[None of the configured nodes are available: 
[{#transport#-1}{cW5XIRlRTaqX5ryP8KV6_A}{172.19.50.200}{172.19.50.200:9200}]]
	at 
	org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:347)
	at
	org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:245)

解决:参考 https://www.jianshu.com/p/ea0bd9d82f6c

此处需要注意两点,意识自身使用的:注意es默认提供的连接端口是9300,不是http_ui协议的9200端口

 

 //从ES中查询数据
    public void test1() throws UnknownHostException {
        //指定ES集群
        Settings setting = Settings.builder().put("cluster.name","my-application").build();
        //注意es默认提供的连接端口是9300,不是http_ui协议的9200端口
        TransportAddress node = new TransportAddress(InetAddress.getByName("xx.xxx.xx.200"), 9300);

        //创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(setting)
                .addTransportAddress(node);

        //get方式数据查询 ,参数为Index,type和id
        GetResponse response = client.prepareGet("fang_index","fct","11").get();

        System.out.println(response.getSourceAsString());
        client.close();
    }

3.我的java操作es的代码demo

(1)我的maven中pom.xml文件内容如下:

		<!--日志start-->        
		<dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!--日志end-->

        <!--使用es的引入的包-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.0.1</version>
        </dependency>

(2)在资源文件夹引入中引入log4j2.properties文件

appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout

rootLogger.level = info
rootLogger.appenderRef.console.ref = console

(3)我的java操作ES的增删改查代码:

package es4test;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;

/**
 * @author fangchangtan
 * @date 2019-07-30 14:40
 */
public class EsDemo {

    private static final String ES_IP = "xxx.xx.xx.200";
    private static final int ES_PORT = 9300;
    private static final String CLUSTER_NAME = "my-application";
    TransportClient esClient;

    public EsDemo() throws UnknownHostException {
        esClient = initEsConn();
    }

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        EsDemo esDemo = new EsDemo();

        esDemo.test4();
        System.out.println("============ app end =======================");

    }

    /**
     * 初始化es的client连接
     * @return
     * @throws UnknownHostException
     */
    public TransportClient initEsConn() throws UnknownHostException {
        //指定ES集群
        Settings setting = Settings.builder().put("cluster.name",CLUSTER_NAME).build();
        TransportAddress node = new TransportAddress(InetAddress.getByName(ES_IP), ES_PORT);

        //创建访问ES服务器的客户端
        TransportClient client = new PreBuiltTransportClient(setting)
                .addTransportAddress(node);
        return client;
    }

    //1.从ES中查询数据
    public void test1() throws UnknownHostException {
        //get方式数据查询 ,参数为Index,type和id
        GetResponse response = esClient.prepareGet("fang_index","fct","11").get();

        System.out.println(response.getSourceAsString());
        esClient.close();
    }


    //2.插入数据
    public void test2() throws IOException {
        XContentBuilder doc = XContentFactory.jsonBuilder()
                .startObject()
                .field("id","1")
                .field("title","我在学习es插入操作")
                .field("content","好好学习,天天向上")
                .endObject();

        //添加一个doc
        IndexResponse response = esClient.prepareIndex("lib5","testadd",null)//id为null,由ES自己生成
                .setSource(doc).get();
        System.out.println(response.status());//打印添加是否成功
        esClient.close();
    }

    //删除文档
    public void test3() throws UnknownHostException {

        DeleteResponse response = esClient.prepareDelete("lib5","testadd","vTrUQWwB1TuZ1J05E1pU")
                .get();
        System.out.println(response.status());//打印添加是否成功
        esClient.close();
    }

    //更新文档
    public void test4() throws IOException, ExecutionException, InterruptedException {
        XContentBuilder mydoc = XContentFactory.jsonBuilder().startObject()
                .field("title", "我在学习ES的修改操作")
                .field("newadd", "新增字段")
                .endObject();
        UpdateRequest request = new UpdateRequest();
        request.index("lib5")
                .type("testadd")
                .id("wDrWQWwB1TuZ1J05i1pq")
                .doc(mydoc);
        UpdateResponse response = esClient.update(request).get();

        System.out.println(response.status());//打印是否成功
        esClient.close();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值