ElasticScearh入门教程

1.下载ElasticScearh:

官网下载
注意下载的版本:7.16.2


在这里插入图片描述

2.解压运行测试:

提示:下载下来解压,进入bin目录,双击运行bat

在这里插入图片描述
访问:http://localhost:9200
提示以下信息安装成功

在这里插入图片描述


3.整合springboot:

新建maven工程,导入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<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>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.4</version>
    </parent>

    <groupId>com.tangshuai</groupId>
    <artifactId>springboot_es</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-data-elasticsearch</artifactId>-->
            <!--<version>2.3.1.RELEASE</version>-->
        <!--</dependency>-->

        <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
    </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <version>2.5.6</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>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.27</version>
        </dependency>

        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

编写配置文件,为了更好的演示效果,连接数据库操作

spring.datasource.url=jdbc:mysql://localhost:3306/books?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

#spring.elasticsearch.rest.uris=http://localhost:9200

实体类

package com.tangshuai.po;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

/**
 * @author TANGSHUAI
 * @version 1.0
 * @date 2022-02-15 13:32
 */
@Data
@TableName("book")
public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;
}

mapper

package com.tangshuai.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tangshuai.po.Book;
import org.springframework.stereotype.Component;

/**
 * @author TANGSHUAI
 * @version 1.0
 * @date 2022-02-15 13:33
 */
@Component
public interface BookMapper extends BaseMapper<Book>{

}

测试类:使用RestHighLevelClient类测试

package com.tangshuai;

import com.alibaba.fastjson.JSONObject;
import com.tangshuai.mapper.BookMapper;
import com.tangshuai.po.Book;
import org.apache.http.HttpHost;
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.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
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.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

/**
 * @author TANGSHUAI
 * @version 1.0
 * @date 2022-02-15 13:51
 */
@SpringBootTest
@MapperScan("com.tangshuai")
public class AppTestES2 {

    @Autowired
    BookMapper bookMapper;
	
	//由于high版本没有与spring整合所已不能使用@Autowired交给spring管理
    RestHighLevelClient restHighLevelClient;

    /**
     * 每个测试方法之前执行
     */
    @BeforeEach
    void setUp() {
        HttpHost hosts = HttpHost.create("http://localhost:9200");
        RestClientBuilder builder = RestClient.builder(hosts);
        restHighLevelClient = new RestHighLevelClient(builder);

    }

    /**
     * 每个测试方法之后执行
     *
     * @throws IOException
     */
    @AfterEach
    void tearDown() throws IOException {
        restHighLevelClient.close();
    }

    /**
     * 创建索引
     *
     * @throws IOException
     */
    @Test
    void testES() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("books");
        restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    }

    /**
     * 创建索引
     *
     * @throws IOException
     */
    @Test
    void testESik() throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("books");
        //设置请求中的参数
        String json = "\n" +
                "{\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" +
                "            \"type\": {\n" +
                "                \"type\": \"keyword\"\n" +
                "            },\n" +
                "            \"description\": {\n" +
                "                \"type\": \"text\",\n" +
                "                \"analyzer\": \"ik_max_word\",\n" +
                "                \"copy_to\":\"all\"\n" +
                "            },\n" +
                "            \"all\": {\n" +
                "                \"type\": \"text\",\n" +
                "                \"analyzer\": \"ik_max_word\"\n" +
                "            }\n" +
                "        }\n" +
                "    }\n" +
                "}";
        request.source(json, XContentType.JSON);

        restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);

    }

    /**
     * 添加文档
     * @throws IOException
     */
    @Test
    void testCreateDoc() throws IOException {
        //添加单个
//        Book book = bookMapper.selectById(1);
//        IndexRequest request=new IndexRequest("books").id(book.getId().toString());
//        String json = JSONObject.toJSONString(book);
//        request.source(json,XContentType.JSON);
//        restHighLevelClient.index(request, RequestOptions.DEFAULT);
        //添加多个
        List<Book> books = bookMapper.selectList(null);
        BulkRequest request=new BulkRequest();
        for (Book book : books) {
            IndexRequest index=new IndexRequest("books").id(book.getId().toString());
            String json = JSONObject.toJSONString(book);
            index.source(json,XContentType.JSON);
            request.add(index);
        }
        restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
    }

    /**
     * 根据id查询
     */
    @Test
    void testGet() throws IOException {
        GetRequest request=new GetRequest("books", "1");
        GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        String json = getResponse.getSourceAsString();
        System.out.println(json);
    }

    /**
     * 按条件查询
     */
    @Test
    void testSerch() throws IOException {
        SearchRequest request=new SearchRequest("books");

        SearchSourceBuilder sourcebuilder=new SearchSourceBuilder();
        sourcebuilder.query(QueryBuilders.termQuery("name", "redis"));
        request.source(sourcebuilder);

        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            System.out.println(sourceAsString);
        }
    }

}

在这里插入图片描述
数据库文件

/*
 Navicat Premium Data Transfer

 Source Server         : 本地环境
 Source Server Type    : MySQL
 Source Server Version : 50722
 Source Host           : localhost:3306
 Source Schema         : books

 Target Server Type    : MySQL
 Target Server Version : 50722
 File Encoding         : 65001

 Date: 15/02/2022 15:59:47
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1, 'springboot good', 'springboot', 'springboot good');
INSERT INTO `book` VALUES (2, 'redis', 'redis', 'redis');
INSERT INTO `book` VALUES (3, 'redis从入门到精通', 'redis从入门到精通', 'redis从入门到精通');
INSERT INTO `book` VALUES (4, 'redis从入门到放弃', 'redis从入门到放弃', 'redis从入门到放弃');
INSERT INTO `book` VALUES (5, 'redis源码解析', 'redis源码解析', 'redis源码解析');

SET FOREIGN_KEY_CHECKS = 1;

在这里插入图片描述


补充,中文分词我用到了ik插件,所以需要导入插件:

下载ik插件
注意:版本要与ElasticScearh版本一致7.16.2,下载时我们需要选择打包的压缩包,不要下载源码文件了

在这里插入图片描述
在这里插入图片描述
下载后在ElasticScearh的plugins目录下新建目录ik,然后把压缩包的文件放进去,重启ElasticScearh即可
在这里插入图片描述
配合postman测试效果更佳

在这里插入图片描述
创建索引
这里指定了id为1,不传自动生成
改成get请求,为根据id查询
改成put请求,为根据id修改
改成delete请求,为根据id删除

在这里插入图片描述

查询单个索引

在这里插入图片描述
查询全部索引

在这里插入图片描述

指定条件查询
在这里插入图片描述
使用ElasticsearchRestTemplate测试(不推荐)旧版本,与spring整合了

package com.tangshuai;

import com.tangshuai.mapper.BookMapper;
import com.tangshuai.po.Book;
import org.junit.jupiter.api.Test;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;

import java.util.List;

/**
 * @author TANGSHUAI
 * @version 1.0
 * @date 2022-02-15 13:51
 */
@SpringBootTest
@MapperScan("com.tangshuai")
public class AppTestES {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private ElasticsearchRestTemplate template;

    @Test
    void fn(){
        List<Book> books = this.bookMapper.selectList(null);
        for (Book book : books) {
            System.out.println(book);
        }
    }

    @Test
    void testES(){
        boolean books2 = template.indexOps(IndexCoordinates.of("books")).create();
        System.out.println(books2);
        NativeSearchQuery builder = new NativeSearchQueryBuilder().build();

        SearchHits<Book> search = template.search(builder, Book.class);
        List<SearchHit<Book>> searchHits = search.getSearchHits();
        searchHits.forEach(bookSearchHit -> {
            Book content = bookSearchHit.getContent();
            System.out.println(content);
        });
    }
}

打开被注释的依赖以及配置文件
spring.elasticsearch.rest.uris=http://localhost:9200

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>2.3.1.RELEASE</version>
        </dependency>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值