ElasticSearch:对文档进行增删改(5)

本编文章续ElasticSearch:搭建测试环境(4)

如果对ElasticSearch是零基础的,请问本站的ElasticSearch基础搭建与教程

配置依赖

<dependencies>
        <!--ES核心API-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>transport</artifactId>
            <version>6.6.2</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.9.1</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
        </dependency>
        <!--json转换包-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
    </dependencies>

添加log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

创建实体类(Article)

package dt2008.domain;

public class Article {

    private Integer id;
    private String title;
    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

Demo2

注意:

代码中的Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();

cluster.name是ES服务器变量的值

elasticsearch是ES服务器的名称

package dt2008;

import dt2008.domain.Article;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.index.IndexRequest;
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.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Test;

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

public class ElasticSearch {

    @Test
    public void demo1() throws UnknownHostException {
        //1. 创建Settings配置信息对象,用于配置ES的集群信息
        //注意:默认的ES集群名称就是elasticsearch
        Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();

        //2. 创建ES传输客户端对象(***),用于操作ES,例如:创建索引库,添加文档,修改文档....
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        //2.1 添加连接ES的信息,例如主机地址,端口
        transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9300));

        //3.使用传输客户端对象创建索引库
        //prepareCreate: 创建索引库
        //get(): 发出请求到ES去执行
        transportClient.admin().indices().prepareCreate("blog2").get();

        //4.释放资源
        transportClient.close();
    }

    /**
     * 添加文档(第一种方式:使用XContentBuild拼装json)
     * @throws Exception
     */
    @Test
    public void text02() throws Exception {
        //1. 创建Settings配置信息对象,用于配置ES的集群信息
        //注意:默认的ES集群名称就是elasticsearch
        Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
        //2. 创建ES传输客户端对象(***),用于操作ES,例如:创建索引库,添加文档,修改文档....
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        //2.1 添加连接ES的信息,例如主机地址,端口
        transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        //3.创建XContentBuild,用于构建json
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
        //4.开始构建json
        xContentBuilder.startObject();
        xContentBuilder.field("id", 1);
        xContentBuilder.field("title", "Dubbo分布式开发");
        xContentBuilder.field("content", "Dubbo是Java开源的远程调用框框");
        xContentBuilder.endObject();

        //5.把文档在ES添加进去
        /**
         * 参数一:索引库名称
         * 参数二:类型名称
         * 参数三:文档的ID(主键),注意:每个索引库下面的文档必须唯一,ID是唯一的
         *
         * prepareIndex: 指定索引,类型和文档ID
         * setSource:设置文档内容
         * get: 发送请求给ES执行
         */
        transportClient.prepareIndex("blog1", "article", "1").setSource(xContentBuilder).get();
        //关闭资源
        transportClient.close();
    }

    /**
     * 批量添加文档(没有使用批量添加API)
     * @throws Exception
     */
    @Test
    public void text03() throws UnknownHostException, JsonProcessingException {
        //1. 创建Settings配置信息对象,用于配置ES的集群信息
        //注意:默认的ES集群名称就是elasticsearch
        Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
        //2. 创建ES传输客户端对象(***),用于操作ES,例如:创建索引库,添加文档,修改文档....
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        //2.1 添加连接ES的信息,例如主机地址,端口
        transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        long start = System.currentTimeMillis();
        for(int i=1; i<=1000; i++){
            //3.创建Article对象
            Article article = new Article();
            article.setId(i);
            article.setTitle(i+"--WebService");
            article.setContent(i+"--WebService是一种跨语言的远程调用技术");
            //4.把Article手动转换为json字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(article);
            //5.设置文档数据
            transportClient.prepareIndex("blog1", "article", i+"").setSource(json, XContentType.JSON).get();
        }
        long end = System.currentTimeMillis();
        System.out.println("总耗时:"+(end-start));
        transportClient.close();
    }

    /**
     * 批量添加文档(使用ES的批量添加API)
     * @throws Exception
     */
    @Test
    public void text04() throws UnknownHostException, JsonProcessingException {
        //1. 创建Settings配置信息对象,用于配置ES的集群信息
        //注意:默认的ES集群名称就是elasticsearch
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //2. 创建ES传输客户端对象(***),用于操作ES,例如:创建索引库,添加文档,修改文档....
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        //2.1 添加连接ES的信息,例如主机地址,端口
        transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        long start = System.currentTimeMillis();
        //3.创建批量请求构造器,用于执行批量操作
        BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
        for(int i=1; i<=1000; i++){
            Article article = new Article();
            article.setId(i);
            article.setTitle(i+"--POI");
            article.setContent(i+"--POI是Java开源的Office读写工具");

            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(article);
            //4.把数据存入BulkRequestBuilder
            //4.1 IndexRequest: 用于指定把数据存入到哪个索引,哪个类型
            IndexRequest indexReader = new IndexRequest("blog1", "article", i+"").source(json, XContentType.JSON);
            bulkRequestBuilder.add(indexReader);
        }

        //5. 执行批处理操作
        bulkRequestBuilder.get();
        long end = System.currentTimeMillis();
        System.out.println("总耗时:"+(end-start));
        transportClient.close();
    }

    /**
     * 修改文档
     * @throws Exception
     */
    @Test
    public void text05() throws UnknownHostException, JsonProcessingException {
        //1. 创建Settings配置信息对象,用于配置ES的集群信息
        //注意:默认的ES集群名称就是elasticsearch
        Settings settings = Settings.builder().put("cluster.name", "elasticsearch").build();
        //2. 创建ES传输客户端对象(***),用于操作ES,例如:创建索引库,添加文档,修改文档....
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        //2.1 添加连接ES的信息,例如主机地址,端口
        transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        //3.创建Article对象
        Article article = new Article();
        article.setId(3);
        article.setTitle("WebService");
        article.setContent("WebService是一种跨语言的远程调用技术");
        //5.把Article手动转换为json字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(article);
        //3.修改文档
        transportClient.prepareUpdate("blog1", "article", "3").setDoc(json, XContentType.JSON).get();
        transportClient.close();
    }

    /**
     * 删除索引库
     * @throws Exception
     */
    @Test
    public void text06() throws UnknownHostException {
        //1. 创建Settings配置信息对象,用于配置ES的集群信息
        //注意:默认的ES集群名称就是elasticsearch
        Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
        //2. 创建ES传输客户端对象(***),用于操作ES,例如:创建索引库,添加文档,修改文档....
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        //2.1 添加连接ES的信息,例如主机地址,端口
        transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        //3.删除索引库
        transportClient.admin().indices().prepareDelete("blog2").get();
        transportClient.close();
    }

}

 

 

 

本站资源除特别声明外,转载文章请声明文章出处
东泰博客 » ElasticSearch:对文档进行增删改(5)

发表评论