SpringBoot:与检索

 

 

1、检索:

我们的应用经常需要添加检索功能,开源的 ElasticSearch 是目前全文搜索引擎的首选。他可以快速的存储、搜索和分析海量数据。Spring Boot通过整合Spring Data ElasticSearch为我们提供了非常便捷的检索功能支持; Elasticsearch是一个分布式搜索服务,提供Restful API,底层基于Lucene,采用多shard(分片)的方式保证数据安全,并且提供自动resharding的功能,github等大型的站点也是采用了ElasticSearch作为其搜索服务,

2、概念

以 员工文档 的形式存储为例:一个文档代表一个员工数据。存储数据到 ElasticSearch 的行为叫做 索引 ,但在索引一个文档之前,需要确定将文档存储在哪里。 一个 ElasticSearch 集群可以 包含多个 索引 ,相应的每个索引可以包含多个 类型 。 这些不同的类型存储着多个 文档 ,每个文档又有 多个 属性 。 类似关系: 索引-数据库 类型-表 文档-表中的记录 属性-列

 

下载安装elasticsearch

docker pull registry.docker-cn.com/library/elasticsearch

拉取镜像后启动镜像:

docker run -d -e ES_JAVA_OPTS="-Xms256m -Xms256m" -p 9200:9200 -p 9300:9300 --name myelasticsearch 5acf0e8da90b

启动成功后 可以访问验证是否启动成功:如下表示成功

 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)、ElasticsearchTemplate 操作es
 *        3)、编写一个 ElasticsearchRepository 的子接口来操作ES;
 *    两种用法:https://github.com/spring-projects/spring-data-elasticsearch
 *    1)、编写一个 ElasticsearchRepository 2)ElasticsearchTemplate


 */

 

1、第一:Jest用法

引入依赖

<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
    <groupId>io.searchbox</groupId>
    <artifactId>jest</artifactId>
    <version>6.3.1</version>
</dependency>

实体类id上面加注解@JestId

利用JestClient操作保存查询等操作

public class Article {

    @JestId
    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;
    }
}
@Autowired
    JestClient jestClient;

    @Test
    public void contextLoads() {
        //1、给Es中索引(保存)一个文档;
        Article article = new Article();
        article.setId(1);
        article.setAuthor("吴承恩");
        article.setContent("西游记是一本好书");
        article.setTitle("西游记");
        //构建一个索引
        Index index = new Index.Builder(article).index("atyb").type("news").build();
        try {
            DocumentResult result = jestClient.execute(index);
            logger.info("{}",result);
        } catch (IOException e) {
            logger.error("错误信息:"+e.getMessage(),e);
        }
    }

    @Test
    public void testSearch() {

        String json = "{\"query\":{\"match\":{\"content\":\"一本好书\"}}}";
        Search build = new Search.Builder(json).addIndex("atyb").addType("news").build();
        try {
            SearchResult execute = jestClient.execute(build);
            logger.info("{}",execute);
        } catch (IOException e) {
            logger.error("错误信息:"+e.getMessage(),e);
        }
    }

 

第二种:ES版本可能有不合适,需要选择合适的版本,可以参考spring官网

2、SpringData ElasticSearch【ES版本有可能不合适】

1)、编写一个 ElasticsearchRepository


public interface BookRepository extends ElasticsearchRepository<Book,Integer> {

    //参照
    // https://docs.spring.io/spring-data/elasticsearch/docs/3.0.6.RELEASE/reference/html/
   public List<Book> findByBookNameLike(String bookName);

}
 @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("atyb").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("atyb").addType("news").build();

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

    可以像jpa一样用。

2)ElasticsearchTemplate

springboot自动配置好了这个可直接使用

保存一个数据
 
 String documentId = "123456";
        SampleEntity sampleEntity = new SampleEntity();
        sampleEntity.setId(documentId);
        sampleEntity.setMessage("some message");
        IndexQuery indexQuery = new IndexQueryBuilder().withId(sampleEntity.getId()).withObject(sampleEntity).build();
        elasticsearchTemplate.index(indexQuery);

也可以保存多个

  @Autowired
        private ElasticsearchTemplate elasticsearchTemplate;

        List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
        //first document
        String documentId = "123456";
        SampleEntity sampleEntity1 = new SampleEntity();
        sampleEntity1.setId(documentId);
        sampleEntity1.setMessage("some message");

        IndexQuery indexQuery1 = new IndexQueryBuilder().withId(sampleEntity1.getId()).withObject(sampleEntity1).build();
        indexQueries.add(indexQuery1);

        //second document
        String documentId2 = "123457";
        SampleEntity sampleEntity2 = new SampleEntity();
        sampleEntity2.setId(documentId2);
        sampleEntity2.setMessage("some message");

        IndexQuery indexQuery2 = new IndexQueryBuilder().withId(sampleEntity2.getId()).withObject(sampleEntity2).build()
        indexQueries.add(indexQuery2);

        //bulk index
        elasticsearchTemplate.bulkIndex(indexQueries);

 

还可以查询分页信息:如下

 @Autowired
        private ElasticsearchTemplate elasticsearchTemplate;

        SearchQuery searchQuery = new NativeSearchQueryBuilder()
        .withQuery(queryString(documentId).field("id"))
        .build();
        Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class);

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值