美文网首页
Spring-boot 集成Elasticsearch

Spring-boot 集成Elasticsearch

作者: 我是顾子晨 | 来源:发表于2019-08-25 15:14 被阅读0次

环境介绍

  1. 操作系统 windows 10
  2. elasticsearch 版本 6.4.3
  3. spring-boot 版本 2.0.4.RELEASE
  4. jdk 版本 1.8.0_161

相关依赖

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

实体及介绍

  1. Article
  2. Author
  3. Tutorial
package org.nm.south.elasticsearch.bean;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by admin on 17/6/1.
 * indexName:对应索引库名称
 * type:对应在索引库中的类型
 * shards:分片数量,默认5
 * replicas:副本数量,默认1
 */
@Data
@Document(indexName = "projectname", type = "article", indexStoreType = "fs", shards = 5, replicas = 1, refreshInterval = "-1")
public class Article implements Serializable {
    @Id
    private Long id;
    /**
     * 标题
     * type:字段类型,是是枚举:FieldType,可以是text、long、short、date、integer、object等
     * text:存储数据时候,会自动分词,并生成索引
     * keyword:存储数据时候,不会分词建立索引
     * Numerical:数值类型,分两类
     * 基本数据类型:long、interger、short、byte、double、float、half_float
     * 浮点数的高精度类型:scaled_float
     * 需要指定一个精度因子,比如10或100。elasticsearch会把真实值乘以这个因子后存储,取出时再还原。
     * Date:日期类型
     * elasticsearch可以对日期格式化为字符串存储,但是建议我们存储为毫秒值,存储为long,节省空间。
     * index:是否索引,布尔类型,默认是true
     * store:是否存储,布尔类型,默认是false
     * analyzer:分词器名称,这里的ik_max_word即使用ik分词器
     */
    private String title;
    /**
     * 摘要
     */
    private String abstracts;
    /**
     * 内容
     */
    private String content;
    /**
     * 发表时间
     */
    private Date postTime;
    /**
     * 点击率
     */
    private Long clickCount;
    /**
     * 作者
     */
    @Field(type = FieldType.Nested)
    private Author author;

    /**
     * 所属教程
     * */
    @Field(type = FieldType.Nested)
    private Tutorial tutorial;
}


package org.nm.south.elasticsearch.bean;
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
@Data
@Document(indexName="projectname",type="author",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
public class Author implements Serializable {
    /**
     * 作者id
     */
    private Long id;
    /**
     * 作者姓名
     */
    private String name;
    /**
     * 作者简介
     */
    private String remark;
}

package org.nm.south.elasticsearch.bean;

import lombok.Data;
import java.io.Serializable;

@Data
public class Tutorial implements Serializable {
    private Long id;
    /**
     * 教程名称
     */
    private String name;
}

repository

package org.nm.south.elasticsearch.dao;

import org.nm.south.elasticsearch.bean.Article;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;

public interface ArticleSearchRepository extends ElasticsearchRepository<Article, Long> {

    List<Article> findArticlesByTitle(String name);
}

测试用例

  1. 一对一的关系可以直接使用 author.content 进行查询
  2. 一对多的关系需要在对象内指定field 的nested 嵌套关系,查询时指定其path
    2.1. 在QueryBuilders.nestedQuery 中第三个参数为:ScoreMode 可以指定如下值这个值会影响父节点的评分
    2.1.1. None 不参与
    2.1.2. Avg 取平均分
    2.1.3. Max 取最大值
    2.1.4. Total 取总分
    2.1.5. Min 取最小
package org.nm.south.elasticsearch;

import cn.hutool.core.collection.CollectionUtil;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nm.south.elasticsearch.bean.Article;
import org.nm.south.elasticsearch.bean.Author;
import org.nm.south.elasticsearch.bean.Tutorial;
import org.nm.south.elasticsearch.dao.ArticleSearchRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
import java.util.List;
import java.util.Optional;

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

    @Autowired
    private ArticleSearchRepository articleSearchRepository;

    /**
     * 主键
     */
    private static final Long ID = 1L;

    /**
     * 新增
     */
    @Test
    public void create() {
        Author author = new Author();
        author.setId(1L);
        author.setName("tianshouzhi");
        author.setRemark("java developer");

        Tutorial tutorial = new Tutorial();
        tutorial.setId(1L);
        tutorial.setName("elastic search");

        Article article = new Article();
        article.setId(ID);
        article.setTitle("springboot integreate elasticsearch");
        article.setAbstracts("springboot integreate elasticsearch is very easy");
        article.setTutorial(tutorial);
        article.setAuthor(author);
        article.setContent("elasticsearch based on lucene,"
                + "spring-data-elastichsearch based on elaticsearch"
                + ",this tutorial tell you how to integrete springboot with spring-data-elasticsearch");
        article.setPostTime(new Date());
        article.setClickCount(1L);
        articleSearchRepository.save(article);
        Assert.assertTrue(articleSearchRepository.existsById(ID));
    }

    @Test
    public void show() {
        Optional<Article> article = articleSearchRepository.findById(ID);
        Assert.assertTrue(article.isPresent());
        String expected = "springboot integreate elasticsearch";
        Assert.assertEquals(expected, article.get().getTitle());
    }

    /**
     * 修改
     */
    @Test
    public void modify() {
        String modifyTitle = "springboot integreate elasticsearch-modify";
        Optional<Article> articleOptional = articleSearchRepository.findById(ID);
        Assert.assertTrue(articleOptional.isPresent());
        Article article = articleOptional.get();
        article.setTitle(modifyTitle);
        articleSearchRepository.deleteById(ID);
        articleSearchRepository.save(article);
        Optional<Article> modifyOptional = articleSearchRepository.findById(ID);
        Assert.assertTrue(modifyOptional.isPresent());
        Assert.assertEquals(modifyTitle, modifyOptional.get().getTitle());
    }

    /**
     * 删除
     */
    @Test
    public void delete() {
        articleSearchRepository.deleteById(ID);
    }


    /**
     * spring-data-elasticsearch 参数命名查询
     */
    @Test
    public void findByName() {
        List<Article> articleList = articleSearchRepository.findArticlesByTitle("springboot");
        Assert.assertTrue(CollectionUtil.isNotEmpty(articleList));
    }

    /**
     * 自定义查询标题
     */
    @Test
    public void consumerTitleQuery() {
        SearchQuery searchQuery = new NativeSearchQuery(QueryBuilders.boolQuery().filter(QueryBuilders.matchQuery("title", "integreate")));
        Page<Article> articleList = articleSearchRepository.search(searchQuery);
        Assert.assertTrue(articleList.getSize() >= 0);
    }

    /**
     * 嵌套查询
     */
    @Test
    public void nestedQuery() {
        /**
         * 一对多时可用
         */
        QueryBuilder orderQuery = QueryBuilders.nestedQuery("author",
                QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("author.remark", "java")),
                ScoreMode.Total);

        /**
         * 一对一时可以不用 nestedQuery
         */
        SearchQuery searchQuery = new NativeSearchQuery(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("author.remark", "java")));
        Page<Article> articleList = articleSearchRepository.search(searchQuery);
        Assert.assertTrue(articleList.getSize() > 0);
    }
}

相关文章

网友评论

      本文标题:Spring-boot 集成Elasticsearch

      本文链接:https://www.haomeiwen.com/subject/uinhectx.html