SpringBoot整合ES

添加依赖

  1. <dependency>
  2. <groupId>org.elasticsearch.client</groupId>
  3. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  4. <version>6.6.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.elasticsearch.client</groupId>
  8. <artifactId>elasticsearch-rest-client</artifactId>
  9. <version>6.6.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.elasticsearch</groupId>
  13. <artifactId>elasticsearch</artifactId>
  14. <version>6.6.2</version>
  15. </dependency>

编写elasticsearch配置类

  1. package cn.itcast.config;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.springframework.boot.context.properties.ConfigurationProperties;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. /**
  9. * ES配置类
  10. *
  11. * @Author LK
  12. * @Date 2021/2/22
  13. */
  14. @Configuration
  15. @ConfigurationProperties(prefix = "elasticsearch")
  16. public class ElasticSearchConfig {
  17. private String host;
  18. private int port;
  19. public void setHost(String host) {
  20. this.host = host;
  21. }
  22. public void setPort(int port) {
  23. this.port = port;
  24. }
  25. @Bean
  26. public RestHighLevelClient restHighLevelClient() {
  27. RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(
  28. new HttpHost(
  29. "192.168.211.129",
  30. 9200,
  31. "http"
  32. )
  33. ));
  34. return restHighLevelClient;
  35. }
  36. }

编写配置文件

elasticsearch:
  host: 192.168.211.129
  port: 9200

创建索引

目标:能够使用highLevelApi创建索引库

1) 创建空索引

/**
 * 添加索引
 */
@Test
public void addIndex() throws Exception{
    // 1.使用client获取操作索引的对象
    IndicesClient indices = client.indices();
    // 2.执行操作,获取返回值
    CreateIndexRequest request = new CreateIndexRequest("itheima");
    CreateIndexResponse response = indices.create(request, RequestOptions.DEFAULT);
    // 3.判断结果
    System.out.println(response.isAcknowledged());
}

运行结果如下:

2) 创建索引并添加映射

/**
 * 创建索引并添加映射
 */
@Test
public void addIndexAndMapping() throws Exception{
    // 1.使用client获取操作索引的对象
    IndicesClient indices = client.indices();
    // 2.执行操作,获取返回值
    CreateIndexRequest request = new CreateIndexRequest("itcast");

    // 2.1 设置映射信息
    String mapping = "{\n" +
            "      \"_doc\" : {\n" +
            "        \"properties\" : {\n" +
            "          \"address\" : {\n" +
            "            \"type\" : \"text\",\n" +
            "            \"analyzer\" : \"ik_max_word\"\n" +
            "          },\n" +
            "          \"age\" : {\n" +
            "            \"type\" : \"integer\"\n" +
            "          },\n" +
            "          \"name\" : {\n" +
            "            \"type\" : \"keyword\"\n" +
            "          }\n" +
            "        }\n" +
            "      }\n" +
            "    }";
    request.mapping("_doc", mapping, XContentType.JSON);

    CreateIndexResponse response = indices.create(request, RequestOptions.DEFAULT);

    // 3.判断结果
    System.out.println(response.isAcknowledged());
}

运行结果如下:

6.3 删除索引

目标:能够使用highLevelApi删除索引库

/**
 * 删除索引
 */
@Test
public void deleteIndex() throws Exception{
    // 1.使用client获取操作索引的对象
    IndicesClient indices = client.indices();
    // 2.执行操作,获取返回值
    DeleteIndexRequest request = new DeleteIndexRequest("itheima");
    AcknowledgedResponse response = indices.delete(request, RequestOptions.DEFAULT);

    // 3.判断结果
    System.out.println(response.isAcknowledged());
}

6.4 添加文档

目标:能够使用highLevelApi添加文档

方式一

/**
 * 添加文档
 */
@Test
public void addDoc() throws Exception {
    // 1.构建文档数据
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("name", "小kk");
    data.put("age", 20);
    data.put("address", "广州天河区");

    // 2.构建请求对象
    // 参数1-索引库名称,参数2-类型名称,参数3-主键id(不指定使用uuid)
    IndexRequest request = new IndexRequest("itcast", "_doc", "1").source(data);

    // 3.执行结果,获取返回结果
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);

    // 4.打印查询结果
    System.out.println(response.getId());
}

运行结果:

方式二

第一步:创建实体类

package cn.itcast.pojo;

/**
 * TODO
 *
 * @Author LK
 * @Date 2021/2/25
 */
public class Person {
    private String id;

    private String name;

    private int age;

    private String address;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

第二步:pom文件添加jackson-databind依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>

第三步:编写测试用例

/**
 * 添加文档,通过对象构建
 */
@Test
public void addDoc2() throws Exception{
    // 1.构建文档数据
    Person data = new Person();
    data.setId("2");
    data.setName("小zz");
    data.setAge(21);
    data.setAddress("广州黄埔区");

    // 1.1 将对象转为json
    String jsonStr = new ObjectMapper().writeValueAsString(data);

    // 2.构建请求对象
    // 参数1-索引库名称,参数2-类型名称,参数3-主键id(不指定使用uuid)
     IndexRequest request = new IndexRequest("itcast", "_doc", data.getId()).source(jsonStr, XContentType.JSON);

    // 3.执行结果,获取返回结果
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);

    // 4.打印查询结果
    System.out.println(response.getId());
}

运行结果:

6.5 修改、查询、删除文档

目标:能够使用highLevelApi添加、修改、删除文档

应用场景:修改、删除文档作用就是同步数据库的数据到ES的索引库中

1)修改文档

/**
 * 修改文档,如果id存在便修改,如果不存在就添加
 */
@Test
public void updateDoc() throws Exception{
    // 1.构建文档数据
    Person data = new Person();
    data.setId("2");
    data.setName("小zzzz");
    data.setAge(22);
    data.setAddress("广州黄埔区");

    // 1.1 将对象转为json
    String jsonStr = new ObjectMapper().writeValueAsString(data);

    // 2.构建请求对象
    // 参数1-索引库名称,参数2-类型名称,参数3-主键id
    IndexRequest request = new IndexRequest("itcast", "_doc", data.getId()).source(jsonStr, XContentType.JSON);


    // 3.执行结果,获取返回结果
    IndexResponse response = client.index(request, RequestOptions.DEFAULT);

    // 4.打印查询结果
    System.out.println(response.getId());
}

以上执行完毕可将id为2的数据修改成data的数据

2)查询文档

/**
 * 根据id查询文档
 * @throws Exception
 */
@Test
public void findDocById() throws Exception {
    // 1.构建请求对象
    // 参数1-索引库名称,参数2-类型名称,参数3-主键id
    GetRequest request = new GetRequest("itcast", "_doc", "1");
    // 2.执行结果,获取返回结果
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    // 3.打印查询结果
    System.out.println(response.getSourceAsString());
}

运行结果:

3)删除文档

/**
 * 根据id删除
 * @throws Exception
 */
@Test
public void deleteDocById() throws Exception {
    // 1.构建请求对象
    // 参数1-索引库名称,参数2-类型名称,参数3-主键id
    DeleteRequest request = new DeleteRequest("itcast", "_doc", "1");
    // 2.执行结果,获取返回结果
    DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
    // 3.打印查询结果
    System.out.println(response.getId());
}

以上执行完毕可将id为1的数据进行删除

6.6 批量操作

目标:能够使用脚本和代码进行批量操作

Bulk 批量操作是将文档的增删改查一些列操作,通过一次请求全都做完。减少网络传输次数。

应用场景:ES索引库数据初始化的时候,可以将数据库的数据查询出来通过批量操作导入到索引库中

脚本操作

语法:

POST _bulk
{"action": {"metadata"}}
{"data"}

示例:

# 1.删除id为5的文档
# 2.添加id为6的文档
# 3.修改id为2的文档
POST _bulk
{"delete":{"_index":"person","_type":"_doc","_id":"5"}}
{"create":{"_index":"person","_type":"_doc","_id":"6"}}
{"name":"六号","age":60,"address":"广州越秀区"}
{"update":{"_index":"person","_type":"_doc","_id":"2"}}
{"doc": {"name":"二号"}}

代码操作

1)编写单元测试用例

/**
 * 批量操作
 */
@Test
public void bulk() throws Exception{
    // 1.创建批量请求对象
    BulkRequest bulkRequest = new BulkRequest();

    // 2.循环添加请求对象
    for (int i = 10; i < 20; i++) {
        IndexRequest indexRequest = new IndexRequest("itcast", "_doc");
        // 2.1.构建文档数据
        Person data = new Person();
        data.setId(i + "");
        data.setName("张" + i);
        data.setAge(20);
        data.setAddress("广州黄埔区");

        // 2.2 将对象转为json
        String jsonStr = new ObjectMapper().writeValueAsString(data);
        indexRequest.source(jsonStr, XContentType.JSON);

        // 2.3 添加请求对象
        bulkRequest.add(indexRequest);
    }

    // 3.执行请求,获取返回结果
    BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);

    // 4.打印执行状态,返回200代表执行成功
    System.out.println(response.status().getStatus());
}