通过Java客户端操作Elasticsearch

1. 创建Maven给工程

添加pom依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo.elasticsearch</groupId>
    <artifactId>Elasticsearch01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <!-- Elasticsearch核心依赖包 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>5.5.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- 日志依赖 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>
    </dependencies>
</project>

2.通过java客户端俩节elasticsearch

注意:9200端口是http协议访问的,如果通过java客户端,需要访问9300端口,

具体代码如下:

import java.net.InetAddress;
import java.net.UnknownHostException;
 
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;

public class ElasticsearchTest1 {
 
    private Logger logger = LoggerFactory.getLogger(ElasticsearchTest1.class);
     
    public final static String HOST = "192.168.1.140";
     
    public final static int PORT = 9300;//http请求的端口是9200,客户端是9300
     
    /**
     * 测试Elasticsearch客户端连接
     */
    @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 Elasticsearch索引库的创建

为了简化代码,我们在修改Junit测试类,在方法执行之前连接Elasticsearch,方法调用之后自动执行关闭Elasticsearch,通过@Before和@After注解实现,具体代码如下

private Logger logger = LoggerFactory.getLogger(ElasticsearchTest2.class);
     
    public final static String HOST = "192.168.1.140";
     
    public final static int PORT = 9300; //http请求的端口是9200,客户端是9300
     
    private TransportClient client = null;
    /**
     * 获取客户端连接信息
     * @throws UnknownHostException 
     */
    @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());
    }
     
    /**
     * 关闭连接
     * @Title: closeConnect 
     * @return void
     */
    @After
    public void closeConnect() {
        if(null != client) {
            logger.info("执行关闭连接操作...");
            client.close();
        }
    }

创建索引库:

    /**
     * 创建索引库
     * @Title: addIndex1
     * @return void
     * 需求:创建一个索引库为:msg消息队列,类型为:tweet,id为1
     * 索引库的名称必须为小写
     * @throws IOException 
     */
    @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", "你好李四")
                .endObject()).get();
         
        logger.info("索引名称:" + response.getIndex() + "\n类型:" + response.getType()
                    + "\n文档ID:" + response.getId() + "\n当前实例状态:" + response.status());
    }

4. 向索引库中添加json字符串

/**
     * 添加索引:传入json字符串
     * @Title: addIndex2 
     * @return void
     */
    @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());
         
    }

5、向索引库添加一个Map集合

/**
     * 创建索引-传入Map对象 
     * @date 2017年11月23日
     * @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());
    }

6、向索引库添加JsonObject

/**
     * 传递json对象
     * 需要添加依赖:gson
     * @Title: addIndex4 
     * @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());
    }

7、从索引库获取数据

    /**
     * 从索引库获取数据
     * @Title: getData1 
     * @return void
     */
    @Test
    public void getData1() {
        GetResponse getResponse = client.prepareGet("msg", "tweet", "1").get();
        logger.info("索引库的数据:" + getResponse.getSourceAsString());
    }

8、更新索引库数据

/**
     * 更新索引库数据
     * @Title: updateData 
     * @return void
     */
    @Test
    public void updateData() {
        JsonObject jsonObject = new JsonObject();
         
        jsonObject.addProperty("userName", "王五");
        jsonObject.addProperty("sendDate", "2008-08-08");
        jsonObject.addProperty("msg","你好,张三,好久不见");
         
        UpdateResponse updateResponse = client.prepareUpdate("msg", "tweet", "1")
                                        .setDoc(jsonObject.toString(),XContentType.JSON).get();
         
        logger.info("updateResponse索引名称:" + updateResponse.getIndex() + "\n updateResponse类型:" + updateResponse.getType()
        + "\n updateResponse文档ID:" + updateResponse.getId() + "\n当前实例updateResponse状态:" + updateResponse.status());
    }

9、删除索引库的数据

/**
     * 根据索引名称,类别,文档ID 删除索引库的数据
     * @Title: deleteData 
     * @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());
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值