SpringBoot集成Elasticsearch

java1234

共 2362字,需浏览 5分钟

 ·

2021-01-11 22:39

点击上方蓝色字体,选择“标星公众号”

优质文章,第一时间送达

  作者 |  Zzzkis

来源 |   urlify.cn/RR7fIz

76套java从入门到精通实战课程分享

1. 准备工作

  需要提前安装好Elasticsearch,访问地址:http://127.0.0.1:9200/ 得到以下结果,得到cluster_name,下面配置使用。

{
  "name" : "O8GslS3",
  "cluster_name" : "docker-cluster",
  "cluster_uuid" : "pviTqfXtR3GtnxF-Po-_aA",
  "version" : {
    "number" : "6.5.0",
    ......
  },
  "tagline" : "You Know, for Search"
}

 

2. 使用Maven创建SpringBoot工程

  配置Maven的pom.xml文件


        org.springframework.boot
        spring-boot-parent
        2.1.6.RELEASE
    


    
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        

    


  注意:spring-boot-starter-data-elasticsearch包,引用的是spring-data-elasticsearch包,而spring-data-elasticsearch包的版本与elasticsearch服务版本是有兼容性问题的。

  目前并不支持elasticsearch7.x,参考:https://github.com/spring-projects/spring-data-elasticsearch

  配置application.yml文件

spring:
  data:
    elasticsearch:
      cluster-name: docker-cluster
      cluster-nodes: 127.0.0.1:9300
      repositories:
        enabled: true


3. 代码

  实体类。使用@Document注解,参数indexName是索引名称,type是type名称。

// indexName索引名称,type类型
@Document(indexName = "houseindex", type = "house")
public class HouseIndexTemplate {

    @Id
    private Long houseId;

    // 使用分词器
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String title;

    @Field(type = FieldType.Keyword)
    private String name;

    @Field(type = FieldType.Integer)
    private int price;


}

  访问接口。使用@Repository注解,并继承ElasticsearchRepository接口,就可以直接访问的。

  有两个参数:1.返回的对象,2.ID参数数据类型

@Repository
public interface HouseRepository extends ElasticsearchRepository<HouseIndexTemplateLong{

}

  测试用例

@RunWith(SpringRunner.class)
@SpringBootTest(classes 
= Application.class)
public class UserServiceTest 
{

    @Autowired
    private HouseRepository houseRepository;

    @Test
    public void selectUser(){        HouseIndexTemplate template = new HouseIndexTemplate();        template.setId(1);        template.setName("Tom");
        houseRepository.save(template);
    }

}

4. 异常解释

  问题1:NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{IVH9QII0QrOU9GkXdsJPiA}{127.0.0.1}{127.0.0.1:9300}]]

  原因:这是说配置的节点不可用,原因答题有3种可能:(1)IP地址或端口填写有误;(2)cluster_name填写有误;(3)Elasticsearch服务已关闭


粉丝福利:Java从入门到入土学习路线图

👇👇👇

👆长按上方微信二维码 2 秒


感谢点赞支持下哈 

浏览 35
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报