Elasticsearch ( ES ) 分布式全文搜索引擎介绍、安装与使用;SpringBoot 整合 ES 代码示例

Elasticsearch ( ES ) 分布式全文搜索引擎介绍、安装与使用;SpringBoot 整合 ES 代码示例

+ Elasticsearch ( ES ) 分布式全文搜索引擎介绍、安装与使用

- 以windows环境为例:
  • 下载 ES :
    https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.16.2-windows-x86_64.zip
  • 解压完成后,执行 bin 下 elasticsearch.bat 启动 ES 服务:
    在这里插入图片描述
  • 验证是否启动成功:访问 localhost:9200,返回如下图所示 JSON 信息,则表示启动成功:
    在这里插入图片描述
- 下载 IK 分词器:
  • https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.16.2/elasticsearch-analysis-ik-7.16.2.zip
  • 将压缩包中的文件解压到下图所示目录后,重启 ES 服务
    在这里插入图片描述
- 通过 Postman 创建索引(PUT请求):
{
    
    
    "mappings":{
    
    
        "properties":{
    
    
            "id":{
    
    
                "type":"keyword"
            },
            "name":{
    
    
                "type":"text",
                "analyzer":"ik_max_word",
                "copy_to":"all"
            },
            "description":{
    
    
                "type":"text",
                "analyzer":"ik_max_word",
                "copy_to":"all"
            },
            "price":{
    
    
                "type":"keyword"
            },
            "all":{
    
    
                "type":"text",
                "analyzer":"ik_max_word"
            }
        }
    }
}

在这里插入图片描述

- 通过 Postman 查询索引(GET请求):

在这里插入图片描述

- 通过 Postman 添加文档(POST请求):
  • 方式一:http://localhost:9200/books/_doc/id,此方式也可在URL中携带参数 id ,也可不在URL中携带 id ,不在URL中携带 id时,id会自动生成。在请求体中携带参数id无效。
    在这里插入图片描述
  • 方式二:http://localhost:9200/books/_create/id,在请求体中携带参数id无效。
    在这里插入图片描述
- 通过 Postman 查询文档(GET请求):
  • http://localhost:9200/books/_doc/2
    在这里插入图片描述
- 通过 Postman 查询全部文档(GET请求):
  • http://localhost:9200/books/_search
    在这里插入图片描述
- 通过 Postman 按条件查询文档(GET请求):
  • http://localhost:9200/books/_search?q=name:springcloud
    在这里插入图片描述
- 通过 Postman 删除文档(DELETE请求):
  • http://localhost:9200/books/_doc/2
    在这里插入图片描述
- 通过 Postman 修改文档(POST请求):
  • http://localhost:9200/books/_update/2,且要携带要修改的参数信息:
    在这里插入图片描述
    在这里插入图片描述

+ SpringBoot 整合 Elasticsearch ( ES ) 代码示例

- pom.xml添加相关依赖:
<dependency>
   <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.28</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>
<!--低版本的客户端依赖-->
<!--<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>-->

<!--高版本的客户端依赖-->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
- yml配置:
spring:
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC
      username: user
      password: 123456

#  低版本的ES客户端配置
#  elasticsearch:
#    uris: http://localhost:9200
#  高版本的ES还未整合,需要硬编码

mybatis-plus:
  global-config:
    db-config:
      table-prefix: tbl_
      id-type: assign_uuid
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
- 创建索引:
  • 测试类代码示例:
import com.example.springboot.dao.BookDao;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class SpringBootESTest {
    
    

//    老版本的客户端
//    @Autowired
//    private ElasticsearchRestTemplate template;

    private RestHighLevelClient client;

    @Test
    void testCreateIndexByIK() {
    
    
        try {
    
    
            HttpHost host = HttpHost.create("http://localhost:9200");
            RestClientBuilder builder = RestClient.builder(host);
            client = new RestHighLevelClient(builder);

            CreateIndexRequest request = new CreateIndexRequest("books");
            // 设置请求中的参数
            String json = "{\n" +
                    "    \"mappings\":{\n" +
                    "        \"properties\":{\n" +
                    "            \"id\":{\n" +
                    "                \"type\":\"keyword\"\n" +
                    "            },\n" +
                    "            \"name\":{\n" +
                    "                \"type\":\"text\",\n" +
                    "                \"analyzer\":\"ik_max_word\",\n" +
                    "                \"copy_to\":\"all\"\n" +
                    "            },\n" +
                    "            \"description\":{\n" +
                    "                \"type\":\"text\",\n" +
                    "                \"analyzer\":\"ik_max_word\",\n" +
                    "                \"copy_to\":\"all\"\n" +
                    "            },\n" +
                    "            \"price\":{\n" +
                    "                \"type\":\"keyword\"\n" +
                    "            },\n" +
                    "            \"all\":{\n" +
                    "                \"type\":\"text\",\n" +
                    "                \"analyzer\":\"ik_max_word\"\n" +
                    "            }\n" +
                    "        }\n" +
                    "    }\n" +
                    "}";
            request.source(json, XContentType.JSON);
            client.indices().create(request, RequestOptions.DEFAULT);

            client.close();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
}
  • 执行测试代码后,通过 Postman 测试:(备注,测试类抛异常了,json无法被正常解析,需要调试下);
    在这里插入图片描述
- 添加文档
  • 测试代码如下:
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.example.springboot.dao.BookDao;
import com.example.springboot.entity.Book;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class SpringBootESTest {
    
    

    @Autowired
    private BookDao bookDao;

//    老版本的客户端
//    @Autowired
//    private ElasticsearchRestTemplate template;

    private RestHighLevelClient client;

    @Test
    void testCreateIndexByIK() {
    
    
        // 创建带IK分词器的索引
        try {
    
    
            HttpHost host = HttpHost.create("http://localhost:9200");
            RestClientBuilder builder = RestClient.builder(host);
            client = new RestHighLevelClient(builder);

            CreateIndexRequest request = new CreateIndexRequest("books");
            // 设置请求中的参数
            String json = "{" +
                    "    \"mappings\":{" +
                    "        \"properties\":{" +
                    "            \"id\":{" +
                    "                \"type\":\"keyword\"" +
                    "            }," +
                    "            \"name\":{" +
                    "                \"type\":\"text\"," +
                    "                \"analyzer\":\"ik_max_word\"," +
                    "                \"copy_to\":\"all\"" +
                    "            }," +
                    "            \"description\":{" +
                    "                \"type\":\"text\"," +
                    "                \"analyzer\":\"ik_max_word\"," +
                    "                \"copy_to\":\"all\"" +
                    "            }," +
                    "            \"price\":{" +
                    "                \"type\":\"keyword\"" +
                    "            }," +
                    "            \"all\":{" +
                    "                \"type\":\"text\"," +
                    "                \"analyzer\":\"ik_max_word\"" +
                    "            }" +
                    "        }" +
                    "    }" +
                    "}";
            request.source(json, XContentType.JSON);
            client.indices().create(request, RequestOptions.DEFAULT);

            client.close();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }

    }

    @Test
    void createDoc(){
    
    
        // 创建文档
        try {
    
    
            HttpHost host = HttpHost.create("http://localhost:9200");
            RestClientBuilder builder = RestClient.builder(host);
            client = new RestHighLevelClient(builder);

            Book book = bookDao.selectById("1");

            // 需要添加相关依赖 fastjson
            String json = JSON.toJSONString(book);

            IndexRequest indexRequest = new IndexRequest("books").id("1");
            indexRequest.source(json, XContentType.JSON);
            client.index(indexRequest, RequestOptions.DEFAULT);

            client.close();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }

    }

    @Test
    void createDocBulk(){
    
    
        // 批处理创建文档
        try {
    
    
            HttpHost host = HttpHost.create("http://localhost:9200");
            RestClientBuilder builder = RestClient.builder(host);
            client = new RestHighLevelClient(builder);

            List<Book> books = bookDao.selectList(null);

            BulkRequest bulkRequest = new BulkRequest();
            for (Book book : books) {
    
    
                String json = JSON.toJSONString(book);
                IndexRequest indexRequest = new IndexRequest("books").id(book.getId());
                indexRequest.source(json, XContentType.JSON);
                bulkRequest.add(indexRequest);
            }

            client.bulk(bulkRequest, RequestOptions.DEFAULT);

            client.close();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
}
  • 通过 Postman 测试如下:
    在这里插入图片描述
- 查询文档
  • 测试代码如下:
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.handlers.FastjsonTypeHandler;
import com.example.springboot.dao.BookDao;
import com.example.springboot.entity.Book;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.naming.directory.SearchResult;
import java.util.List;

@SpringBootTest
public class SpringBootESTest {
    
    

    @Autowired
    private BookDao bookDao;

//    老版本的客户端
//    @Autowired
//    private ElasticsearchRestTemplate template;

    private RestHighLevelClient client;

    @Test
    void queryDocById(){
    
    
        // 按id查询文档
        try {
    
    
            HttpHost host = HttpHost.create("http://localhost:9200");
            RestClientBuilder builder = RestClient.builder(host);
            client = new RestHighLevelClient(builder);
            GetRequest request = new GetRequest("books", "1");
            GetResponse response = client.get(request, RequestOptions.DEFAULT);
            String json = response.getSourceAsString();
            System.out.println(json);
            // 执行结果如下:
            // {"description":"这是一本关于springboot框架的书籍,价格是50元","id":"1","name":"springboot从入门到精通","price":50}

            client.close();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }

    }

    @Test
    void queryDocSearch(){
    
    
        // 按条件查询
        try {
    
    
            HttpHost host = HttpHost.create("http://localhost:9200");
            RestClientBuilder builder = RestClient.builder(host);
            client = new RestHighLevelClient(builder);

            SearchRequest searchRequest = new SearchRequest("books");
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(QueryBuilders.termQuery("name", "springcloud"));
            // searchSourceBuilder.query(QueryBuilders.termQuery("all", "springcloud"));
            searchRequest.source(searchSourceBuilder);

            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
    
    
                System.out.println(hit.getSourceAsString());
            }

            // 查出一条记录,执行结果如下:
            // {"description":"这是一本关于springcloud框架的书籍,价格是50元","id":"2","name":"springcloud从入门到精通","price":50}

            client.close();
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
}
  • 完结

猜你喜欢

转载自blog.csdn.net/qq_38132105/article/details/125959999