java操作elasticsearch 5.6.0查询、插入

需注意:

1、ES5*以上版本需要jdk1.8

2、1.8JDK需tomcat 8



一、新建maven项目,添加依赖


		
			junit
			junit
			4.9
		
		
			jdk.tools
			jdk.tools
			1.8
			system
			C:/Program Files/Java/jdk1.8.0_144/lib/tools.jar
		

		
            org.elasticsearch
            elasticsearch
            5.6.0
        
		
			org.elasticsearch.client
			transport
			5.6.0
		
		
			org.apache.logging.log4j
			log4j-api
			2.7
		
		
			org.apache.logging.log4j
			log4j-core
			2.7
		
	
二、新建log4j相关文件

在main文件夹下新建resource文件夹,新建log4j.properties和log4j2.xml

log4j.properties

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

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

log4j2.xml




    

       

          

       

    

    

       

          

       

    


三、查询

在es中新建索引/blog/article ,插入几条数据;
(注意:这里IP地址写自己在elasticsearch.yml中写的network.host,port就写9300,虽然自己设置的es集群port是9200

    public static void main(String[] args) {
    try {
    	
        //设置集群名称

        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //创建client
        @SuppressWarnings("resource")
		TransportClient client = new PreBuiltTransportClient(settings)
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("0.0.0.0"), 9300));
        //写入数据
       // createDate(client);
        //搜索数据
        GetResponse response = client.prepareGet("blog", "article", "1").execute().actionGet();
        //输出结果
        System.out.println(response.getSource());
        
        //关闭client
        client.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    }

 
  

四、插入单条数据

(因为在查询时已经创建client,因此这里直接引入了,单独插入需单独创建)

 /**
    * 插入单条数据
    * @param client
    */
    public static void createDate(Client client){
    	Map map = new HashMap();
    	map.put("title", "红楼梦");
    	map.put("content", "重生之我是贾宝玉");
    	map.put("newcontent", new String[]{"first","我是贾宝玉"}) ;
    	map.put("about", "i'd like to play");
    	try {
    		IndexResponse response = client.prepareIndex("blog", "article",UUID.randomUUID().toString())
                    .setSource(map).execute().actionGet();
    		System.out.println("写入数据结果=" + response.status().getStatus() + "!id=" + response.getId());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}


java操作elasticsearch 5.6.0查询、插入_第1张图片


你可能感兴趣的:(elasticsearch)