Back End

SpringBoot与检索

PineappleCat · 5月11日 · 2020年 503次已读

我们的应用经常需要添加检索功能,开源的ElasticSearch是目前全文搜索引擎的首选。可以快速的存储、搜索和分析海量数据Spring Boot通过整合Spring Data ElasticSearch为我们提供了非常便捷的检索功能支持;
Elasticsearch 是 面向文档 的,意味着它存储整个对象或 文档。Elasticsearch 不仅存储文档,而且 索引 每个文档的内容,使之可以被检索。在 Elasticsearch 中,我们对文档进行索引、检索、排序和过滤—​而不是对行列数据。这是一种完全不同的思考数据的方式,也是 Elasticsearch 能支持复杂全文检索的原因。
Elasticsearch 使用 JavaScript Object Notation(或者 JSON)作为文档的序列化格式。
关系图:
file
对比Mysql,索引类似于数据库,类型类似于表,文档类似于表,属性类似于字段。
官网文档:https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html (非开新标签页)
其中官网文档中简单例子可按照,基础入门-> 你知道的, 为了搜索…->面向文档,其中的索引员工文档案例中有一些概念的理解值得去阅读实践。推荐在dockers中安装ElasticSearch,自行百度,或留言,这里不赘述。

SpringBoot整合ElasticSearch

```
/**
 * SpringBoot默认支持两种技术来和ES交互;
 * 1、Jest(默认不生效)见测试类
 *  需要导入jest的工具包(io.searchbox.client.JestClient)
 *
 * 2、SpringData ElasticSearch【ES版本有可能不合适】
 *      版本适配说明:https://github.com/spring-projects/spring-data-elasticsearch
 *      如果版本不适配:2.4.6
 *          1)、升级SpringBoot版本
 *          2)、安装对应版本的ES
 *
 *      1)、配置Client 节点信息clusterNodes;clusterName
 *      2)、实现1:ElasticsearchTemplate 操作es
 *      3)、实现2:编写一个 ElasticsearchRepository 的子接口来操作ES;
 *  两种用法:https://github.com/spring-projects/spring-data-elasticsearch
 *      1)、编写一个 ElasticsearchRepository
 */
```

Jest方式

1.注释SpringBoot默认使用的Spring Data ElasticSearch,导入Jest的pom。

```
        <!--SpringBoot默认使用SpringData ElasticSearch模块进行操作-->
<!--         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency> -->
        <!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>5.3.3</version>
        </dependency>
```

2.在application.properties中配置

#Jest的主机地址
spring.elasticsearch.jest.uris=http://xxxxxx:9200   

http://xxxxxx:9200 为我的虚拟机的地址。
3.Jest进行测试
创建Article实体类

import io.searchbox.annotations.JestId;

public class Article {

    @JestId //标识id是一个主键
    private Integer id;

    private String author;
    private String title;
    private String content;

    public Integer getId() {
        return id;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    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;
    }
}

测试类

import com.atguigu.elastic.bean.Article;
import com.atguigu.elastic.bean.Book;
import com.atguigu.elastic.repository.BookRepository;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot03ElasticApplicationTests {

//Jest(默认不生效)
    @Autowired
    JestClient jestClient;

    @Test
    public void contextLoads() {
        //1、给Es中索引(保存)一个文档;
        Article article = new Article();
        article.setId(1);
        article.setTitle("好消息");
        article.setAuthor("zhangsan");
        article.setContent("Hello World");

        //构建一个索引功能
        Index index = new Index.Builder(article).index("atguigu").type("news").build();

        try {
            //执行
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //测试搜索
    @Test
    public void search(){

        //查询表达式
        String json ="{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"content\" : \"hello\"\n" +
                "        }\n" +
                "    }\n" +
                "}";

        //更多操作:https://github.com/searchbox-io/Jest/tree/master/jest
        //构建搜索功能
        Search search = new Search.Builder(json).addIndex("atguigu").addType("news").build();

        //执行
        try {
            SearchResult result = jestClient.execute(search);
            System.out.println(result.getJsonString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Spring Data ElasticSearch方式

1.打开Spring Data ElasticSearch的pom,jest不用关

```
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
```

2.在application.properties中配置

#Jest的主机地址
#SpringData ElasticSearch 节点的名字
spring.data.elasticsearch.cluster-name=elasticsearch
#和jest分开了测试,又开了一个端口
spring.data.elasticsearch.cluster-nodes=192.168.3.17:9301

3.版本适配
file
4.方式其中的ElasticsearchRepository进行测试
Book实体类

import org.springframework.data.elasticsearch.annotations.Document;
//一定要标注注解 索引+类型
@Document(indexName = "atguigu",type = "book")
public class Book {
    private Integer id;
    private String bookName;
    private String author;

    public Integer getId() {
        return id;
    }

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

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bookName='" + bookName + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

5.编写一个 ElasticsearchRepository 的子接口来操作ES

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

//操作的类型 ,其中的主键
public interface BookRepository extends ElasticsearchRepository {

    //可以自定义
    //参照https://docs.spring.io/spring-data/elasticsearch/docs/3.0.6.RELEASE/reference/html/
    //命名方法,相当于发送了什么表达式
   public List findByBookNameLike(String bookName);

}

6.测试类

import com.atguigu.elastic.bean.Article;
import com.atguigu.elastic.bean.Book;
import com.atguigu.elastic.repository.BookRepository;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot03ElasticApplicationTests {

//ElasticsearchRepository
    @Autowired
    BookRepository bookRepository;

    @Test
    public void test02(){
        //保存举例
/*      Book book = new Book();
        book.setId(1);
        book.setBookName("西游记");
        book.setAuthor("吴承恩");
        bookRepository.index(book);*/

        //自定义模糊查询
        for (Book book : bookRepository.findByBookNameLike("游")) {
            System.out.println(book);
        }

    }

浏览器测试

http://xxxxxx:9200/索引/主键

如有见解,欢迎留言。


Click here to view the copyright notice of this site(点击此处查看本站版权声明)


0 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!