springboot整合ElasticSearch

检索:

我们经常需要添加检索功能,开源的ElasticSearch是目前全文搜索引擎的首选,它可以快速存储,搜索和分析海量数据。Spring Boot通过整合Spring Data ElasticSearch为我们提供了非常便捷的检索功能支持。

ElasticSearch是一个分布式搜索服务,提供了Restful API,底层基于Lucene,采用多shard(分片)的方式保证数据安全,并且提供自动resharding功能,github等大型的站点也是采用Elastic Search作为其搜索服务。

ElasticSearch是面向文档的,他存储整个对象或文档。在ElasticSearch中,你对文档进行索引,检索,排序和过滤,而不是对行列数据。

概念:

以员工文档的形式存储为例:一个文档代表一个员工数据,存储数据到ElasticSearch的行为叫做索引,但在索引一个文档之前,需要确定将文档存储在哪里。

一个ElasticSearch集群可以包含多个索引,相应的每个索引可以包含多个类型。这些不同的类型存储着多个文档,每个文档又有多个属性。

对应关系:

        *索引-数据库

        *类型-表

        *文档-表中的记录

        *属性-列

使用:

以索引库megacorp,类型employee,文档id为例:

存储:使用PostMan向ElasticSearch存储数据:地址:http://localhost:9200/megacorp/employee/1,消息体为JSON格式,请求方式为PUT。

基本增删改查:

将PUT请求替换为GET即可,DELETE为删除,HEAD为检测有无。

轻量搜索:

请求所有信息:GET /megacrop/employee/_search

条件搜索: GET /megacorp/employee/_search?q=last_name:xuyu

使用查询表达式搜索:

POST /megacorp/employee/_search

{
    "query" : {
        "bool" : {
            "must" : {
                "match" : {
                    "last_name" : "xuyu"
                }
            },
            "filter" : {
                "range" : {
                    "age" : {"gt" : 30}
                }
            }
        }
    }
}

springboot整合ElasticSearch

1.引入spring-boot-starter-data-elasticsearch

2.安装Spring Data对应版本的ElasticSearch

3.application.yml配置

4.Springboot自动配置的ElasticSearchRepository,ElasticSearchTemplate,Client

5.测试。

导入pom:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>5.3.3</version>
        </dependency>

实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "xuyu",type="book")  //加上索引注解
public class Book {
    private Integer id;

    private String bookName;

    private String author;
}

实现类:

import com.bootbootboot.springboot01cache.bean.Article;
import com.bootbootboot.springboot01cache.bean.Book;
import com.bootbootboot.springboot01cache.repository.BookRepository;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

public class ElasticSearchService {
    /**
     * 检索
     *  springboot默认支持2种技术和ES交互:
     *      1.Jest(默认不生效,需要导入jest工具包(io.searchbox.client.JestClient))
     *      2.SpringData ElasticSearch
     *          1.client节点信息clusterNodes : clusterName
     *          2.ElasticsearchTemplate操作es
     *          3.编写一个ElasticSearchRepository的子接口来操作ES
     *          注意:ES版本不适配问题,版本适配说明:https://github.com/spring-projects/spring-data-elasticsearch。如果版本不适配:
     *              1.升级SpringBoot版本
     *              2.安装对应版本的ES
     *          两种用法:
     *              1.编写一个ElasticsearchRepository
     */
    /*************通过Jest整合ES******************/
    @Autowired
    JestClient jestClient;

    public void jestSave() {
        //1.给ES中索引(保存)一个文档
        Article article = new Article();
        article.setId(1);
        article.setTitle("goodnews");
        article.setAuthor("xuyu");
        article.setContent("hello world!");

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

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

    //搜索
    public void jestSearch(){

        String json="{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"content\" : \"hello\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        //构建搜索
        Search search = new Search.Builder(json).addIndex("xuyu").addType("news").build();
        //执行
        try {
            SearchResult execute = jestClient.execute(search);
            String jsonString = execute.getJsonString();
            System.out.println(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /***********************end****************************/

    /***********************ElasticsearchTemplate操作es*************/

    @Autowired
    BookRepository bookRepository;
    //保存
    public void templateSave(){
        Book book = new Book(1,"xuyu","xuyu");  //需要在类上加@Document(indexName = "xuyu",type="book")注解
        bookRepository.index(book);
    }

    //查询
    public void templateFind(){
        for (Book book : bookRepository.findByBookNameLike("x")) {
            System.out.println(book);
        }
    }
    /*************************end*************************************/
}
public interface BookRepository extends ElasticsearchRepository<Book, Integer> {
    //支持自定义查询
    public List<Book> findByBookNameLike(String bookName);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值