elasticsearch 增删改查

原创 2018年04月17日 09:42:31

        之前在项目中用过ES,但是只写了一小部分代码,从0到增删改查还不会,今天就写了一个简单的增删改查,给大家分享一下。

1、引入jar

 
<!-- log4j日志文件管理包版本 -->  
       <slf4j.version>1.7.13</slf4j.version>  
       <log4j.version>1.2.17</log4j.version> 
<!-- 添加ES --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>5.5.2</version> </dependency>

<!-- 日志文件管理包 -->  
       <!-- log start -->  
       <dependency>  
           <groupId>log4j</groupId>  
           <artifactId>log4j</artifactId>  
           <version>${log4j.version}</version>  
       </dependency>  
     
       <dependency>  
           <groupId>org.slf4j</groupId>  
           <artifactId>slf4j-log4j12</artifactId>  
           <version>1.7.13</version>  
       </dependency>  
       
       <!-- log end -->  

<!--单元测试依赖 -->  
       <dependency>  
           <groupId>junit</groupId>  
           <artifactId>junit</artifactId>  
           <version>4.11</version>  
           <!-- 表示开发的时候引入,发布的时候不会加载此包 -->  
           <scope>test</scope>  
       </dependency>  

2、编写连接ES代码

package es;

/**
 * Created by anzy on 2018/4/16.
 */

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Elasticsearch的基本测试
 * 刚开始报 java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/filter/TokenFilte
 * 在pom中去掉引入的com.fasterxml.就好了
 *
 * @ClassName: ElasticsearchTest1
 * @author anzy
 * @version V1.0
 */
public class ElasticsearchTest {

    private Logger logger = LoggerFactory.getLogger(ElasticsearchTest.class);

    public final static String HOST = "172.25.7.18";

    public final static int PORT = 9300;//http请求的端口是9200,客户端是9300

    /**
     * 测试Elasticsearch客户端连接
     * @Title: test1
     * @author anzy
     * @return void
     * @throws UnknownHostException
     */
    @SuppressWarnings("resource")
    @Test
    public void test1() throws UnknownHostException {
        //创建客户端
        TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
                new InetSocketTransportAddress(InetAddress.getByName(HOST),PORT));
        logger.debug("Elasticsearch connect info:" + client.toString());
        //关闭客户端
        client.close();
    }
}
3、利用spring的测试包编写增删改查

package es;

import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 为了简化代码,我们在修改Junit测试类,在方法执行之前连接Elasticsearch,
 * 方法调用之后自动执行关闭Elasticsearch,通过@Before和@After注解实现
 * <p>
 * Created by anzy on 2018/4/16.
 */
public class ElasticsearchTest2 {

    private Logger logger = LoggerFactory.getLogger(ElasticsearchTest2.class);

    public final static String HOST = "localhost";

    public final static int PORT = 9300; //http请求的端口是9200,客户端是9300

    private TransportClient client = null;

    /**
     * 获取客户端连接信息
     *
     * @return void
     * @Title: getConnect
     * @author anzy
     * @date 2017年11月23日
     */
    @SuppressWarnings({"resource", "unchecked"})
    @Before
    public void getConnect() throws UnknownHostException {
        client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
                new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
        logger.info("连接信息:" + client.toString());
    }

    /**
     * 创建索引库
     *
     * @return void
     * 需求:创建一个索引库为:msg消息队列,类型为:tweet,id为1
     * 索引库的名称必须为小写
     * @throws IOException
     * @Title: addIndex1
     * @author anzy
     * @date 2017年11月23日
     */
    @Test
    public void addIndex1() throws IOException {
        IndexResponse response = client.prepareIndex("msg", "tweet", "1").setSource(XContentFactory.jsonBuilder()
                .startObject().field("userName", "张三")
                .field("sendDate", new Date())
                .field("msg", "你好李四1")
                .endObject()).get();

        logger.info("索引名称:" + response.getIndex() + "\n类型:" + response.getType()
                + "\n文档ID:" + response.getId() + "\n当前实例状态:" + response.status());
    }

    /**
     * 添加索引:传入json字符串
     *
     * @return void
     * @Title: addIndex2
     * @author anzy
     */
    @Test
    public void addIndex2() {
        String jsonStr = "{" +
                "\"userName\":\"张三\"," +
                "\"sendDate\":\"2017-11-30\"," +
                "\"msg\":\"你好李四\"" +
                "}";
        IndexResponse response = client.prepareIndex("weixin", "tweet").setSource(jsonStr, XContentType.JSON).get();
        logger.info("json索引名称:" + response.getIndex() + "\njson类型:" + response.getType()
                + "\njson文档ID:" + response.getId() + "\n当前实例json状态:" + response.status());

    }
    /**
     * 创建索引-传入Map对象
     * @Title: addIndex3
     * @author anzy
     * @return void
     */
    @Test
    public void addIndex3() {
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("userName", "张三");
        map.put("sendDate", new Date());
        map.put("msg", "你好李四");

        IndexResponse response = client.prepareIndex("momo", "tweet").setSource(map).get();

        logger.info("map索引名称:" + response.getIndex() + "\n map类型:" + response.getType()
                + "\n map文档ID:" + response.getId() + "\n当前实例map状态:" + response.status());
    }
    /**
     * 传递json对象
     * 需要添加依赖:gson
     * @Title: addIndex4
     * @author anzy
     * @return void
     */
    @Test
    public void addIndex4() {
//        JsonObject jsonObject = new JsonObject();
//        jsonObject.addProperty("userName", "张三");
//        jsonObject.addProperty("sendDate", "2017-11-23");
//        jsonObject.addProperty("msg","你好李四");
//
//        IndexResponse response = client.prepareIndex("qq", "tweet").setSource(jsonObject, XContentType.JSON).get();
//
//        logger.info("jsonObject索引名称:" + response.getIndex() + "\n jsonObject类型:" + response.getType()
//                + "\n jsonObject文档ID:" + response.getId() + "\n当前实例jsonObject状态:" + response.status());
    }

    /**
     * 从索引库获取数据
     * @Title: getData1
     * @author anzy
     * @date 2017年11月23日
     * @return void
     */
    @Test
    public void getData1() {
        GetResponse getResponse = client.prepareGet("msg", "tweet", "1").get();
        logger.info("索引库的数据:" + getResponse.getSourceAsString());
    }
    /**
     * 更新索引库数据
     * @Title: updateData
     * @author anzy
     * @return void
     */
    @Test
    public void updateData() {
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("userName", "张三");
        map.put("sendDate", new Date());
        map.put("msg", "你好李四更新");
        UpdateResponse updateResponse = client.prepareUpdate("msg", "tweet", "1")
                .setDoc(map, XContentType.JSON).get();

        logger.info("updateResponse索引名称:" + updateResponse.getIndex() + "\n updateResponse类型:" + updateResponse.getType()
                + "\n updateResponse文档ID:" + updateResponse.getId() + "\n当前实例updateResponse状态:" + updateResponse.status());
    }
    @Test
    public void addData(){
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("userName", "张三");
        map.put("sendDate", new Date());
        map.put("msg", "你好李四更新");
        IndexResponse response = client.prepareIndex("momo", "tweet1","1").setSource(map).get();

    }
    /**
     * 根据索引名称,类别,文档ID 删除索引库的数据
     * @Title: deleteData
     * @author anzy
     * @return void
     */
    @Test
    public void deleteData() {
        DeleteResponse deleteResponse = client.prepareDelete("msg", "tweet", "1").get();

        logger.info("deleteResponse索引名称:" + deleteResponse.getIndex() + "\n deleteResponse类型:" + deleteResponse.getType()
                + "\n deleteResponse文档ID:" + deleteResponse.getId() + "\n当前实例deleteResponse状态:" + deleteResponse.status());
    }

    /**
     * 关闭连接
     *
     * @return void
     * @Title: closeConnect
     * @author anzy
     * @date 2017年11月23日
     */
    @After
    public void closeConnect() {
        if (null != client) {
            logger.info("执行关闭连接操作...");
            client.close();
        }
    }
}

我遇到的坑:在运行插入索引时报错(NoNodeAvailableException[None of the configured nodes are available:),原因是我在网上安装head插件的时候改了里面的某些配置引起的。(具体为什么我还没查出来原因)。

希望对大家有帮助啊 ,啦啦啦啦啦啦







版权声明:本文为博主anzy原创文章,转载请注明地址 http://blog.csdn.net/qq_24549805 https://blog.csdn.net/qq_24549805/article/details/79969845

JDBC基础视频课程

了解JDBC的概念和 必要性 了解JDBC驱动程序类型 了解java.sql包 使用JDBC进行 数据库编程 PreparedStatement接口 了解事务
  • 2016年10月13日 14:20

Elasticsearch(三)-分布式增删改查和搜索

Elasticsearch分布式增删改查和搜索
  • WSYW126
  • WSYW126
  • 2017-04-29 11:05:28
  • 436

JAVA API调用elasticsearch实现基本增删改查

1、新增 2、查询 3、修改 4、删除
  • zhuximengbing
  • zhuximengbing
  • 2017-05-24 17:10:49
  • 1348

Java之Elasticsearch 增删改查

package com.sxis.util; import java.io.IOException; import java.net.InetAddress; import java.net.Unk...
  • u012272186
  • u012272186
  • 2017-07-13 15:39:24
  • 1138

ElasticSearch入门-增删改查(java api)

1.增加Index PutMappingRequest mapping = Requests.putMappingRequest(indices).type(mappingType).source...
  • lu_wei_wei
  • lu_wei_wei
  • 2016-03-23 09:54:25
  • 6956

Elasticsearch增删改查

增删改查 增删改查是数据库的基础操作方法。ES 虽然不是数据库,但是很多场合下,都被人们当做一个文档型 NoSQL 数据库在使用,原因自然是因为在接口和分布式架构层面的相似性。虽然在 Elastic...
  • u013063153
  • u013063153
  • 2017-01-17 15:46:14
  • 1391

ElasticSearch 增删改查

0 概述 本文主要介绍使用java API 对ElasticSearch 的增删改查的操作,以及在增删改查中遇到的问题...
  • huangshanchun
  • huangshanchun
  • 2017-04-29 15:45:51
  • 966

ElasticSearch Java 增删改查

ElasticSearch Java 增删改查 package com.earclouds.elasticsearch; import static org.elasticsearch.comm...
  • daiyutage
  • daiyutage
  • 2016-08-26 15:53:00
  • 1765

ElasticSearch Java API(二)增删改查

现在我们来详细的阐述API的CRUD命令(Create,Retrieve,Update,Delete document)。1. 读取文档 GetResponse response = client.p...
  • u013709270
  • u013709270
  • 2016-12-17 18:07:30
  • 1771

ElasticSearch入门-增删改查(CRUD)

ElasticSearch(名称太长,后面简称ES)作为一个搜索引擎,目前可谓是如日中天,几乎和solr齐驾并驱。关于他能做什么,跟云计算有什么关系,在此不再描述。但是ES的官方文档,特别是关于jav...
  • nnn9223643
  • nnn9223643
  • 2015-02-10 17:34:41
  • 1821
收藏助手
不良信息举报
您举报文章:elasticsearch 增删改查
举报原因:
原因补充:

(最多只允许输入30个字)