SpringBoot2.X整合elasticsearch'

SpringBoot默认支持两种技术来和ES交互;

创建项目需要引入ES的启动器

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>
<!--集合工具包--><dependency>    <groupId>com.google.guava</groupId>    <artifactId>guava</artifactId>    <version>19.0</version></dependency>

第一种:

1、Jest(默认不生效)   需要导入jest的工具包(io.searchbox.client.JestClient)

操作步骤:

  1) 引入jest的依赖

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

  2)在配置文件中jest添加相关配置

#使用jest客户端操作ESspring.elasticsearch.jest.uris=http://10.2.193.102:9200

  3)使用jest客户端操作ES

import cn.xiwei.springboot.es.bean.Article;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;

@RunWith(SpringRunner.class)@SpringBootTestpublic class EsApplicationTests {

    @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("xiwei").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" +                "}";        Search search = new Search.Builder(json).addIndex("xiwei").addType("news").build();

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

}

第二种:
1、SpringData ElasticSearch【ES版本有可能不合适】
  * 版本适配说明:https://github.com/spring-projects/spring-data-elasticsearch
  * 如果版本不适配:2.4.6
  * 1)、升级SpringBoot版本
  * 2)、安装对应版本的ES

  1)、Client 节点信息clusterNodes;clusterName

#ES集群的名称spring.data.elasticsearch.cluster-name=my-application 

#Es节点的访问地址及端口spring.data.elasticsearch.cluster-nodes=10.2.193.102:9300

#开启repositoriesspring.data.elasticsearch.repositories.enabled=true

#项目端口号server.port=8080

  2)、ElasticsearchTemplate 操作es (略)

  3)、编写一个 ElasticsearchRepository 的子接口来操作ES;

import cn.xiwei.springboot.es.bean.Notice;import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;import org.springframework.stereotype.Component;

@Componentpublic interface NoticeRepository extends ElasticsearchRepository<Notice, Long> {

}

  4)、测试

import cn.xiwei.springboot.es.bean.Notice;import cn.xiwei.springboot.es.repository.NoticeRepository;import com.google.common.collect.Lists;import org.elasticsearch.index.query.QueryBuilder;import org.elasticsearch.index.query.QueryBuilders;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.domain.Pageable;import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;import org.springframework.data.web.PageableDefault;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;import java.util.List;

/** * @author lykan * @create 2019-09-11 18:40 */@RestController@RequestMapping("/api/v1/article")public class NoticeController {

    @Autowired    private NoticeRepository nticeRepository;

    @Autowired    ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping("/save")    public Object save(long id, String title){

        Notice article = new Notice();        article.setId(id);        article.setReadCount(123);        article.setTitle(title);        return nticeRepository.save(article);    }

    /**     * @param title   搜索标题     * @param pag page = 第几页参数, value = 每页显示条数     */    @GetMapping("/search")    public Object search(String title ,@PageableDefault() Pageable pag){

        //按标题进行搜索        QueryBuilder builder = QueryBuilders.matchQuery("title", title);        //如果实体和数据的名称对应就会自动封装,pageable分页参数        Iterable<Notice> listIt =  nticeRepository.search(builder, pag);        //Iterable转list        List<Notice> list= Lists.newArrayList(listIt);

        return list;    }

    @RequestMapping("/all")    public List<Notice> all() throws Exception {        Iterable<Notice> data = nticeRepository.findAll();        List<Notice> ds = new ArrayList<>();        for (Notice d : data) {            ds.add(d);        }        return ds;    }    @RequestMapping("/id")    public Object findid(long id) throws Exception {        return nticeRepository.findById(id).get();

    }

}

  5)、实体类

import com.fasterxml.jackson.annotation.JsonProperty;import org.springframework.data.elasticsearch.annotations.Document;

/** * @author lykan * @create 2019-09-11 18:00 *///indexName代表所以名称,type代表表名称@Document(indexName = "wantu_notice_info", type = "doc")public class Notice {    //id    @JsonProperty("auto_id")    private Long id;    //标题    @JsonProperty("title")    private String title;    //公告标签    @JsonProperty("exchange_mc")    private String exchangeMc;    //公告发布时间    @JsonProperty("create_time")    private String originCreateTime;    //公告阅读数量    @JsonProperty("read_count")    private Integer readCount;    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getTitle() {        return title;    }    public void setTitle(String title) {        this.title = title;    }    public String getExchangeMc() {        return exchangeMc;    }    public void setExchangeMc(String exchangeMc) {        this.exchangeMc = exchangeMc;    }    public String getOriginCreateTime() {        return originCreateTime;    }    public void setOriginCreateTime(String originCreateTime) {        this.originCreateTime = originCreateTime;    }    public Integer getReadCount() {        return readCount;    }    public void setReadCount(Integer readCount) {        this.readCount = readCount;    }    public Notice(Long id, String title, String exchangeMc, String originCreateTime, Integer readCount) {        super();        this.id = id;        this.title = title;        this.exchangeMc = exchangeMc;        this.originCreateTime = originCreateTime;        this.readCount = readCount;    }    public Notice() {        super();    }}

  
  两种用法:https://github.com/spring-projects/spring-data-elasticsearch

SpringBoot2.X整合elasticsearch'

原文地址:https://www.cnblogs.com/shsgshn/p/11508133.html

时间: 2024-08-16 04:41:01

SpringBoot2.X整合elasticsearch'的相关文章

Spring Boot 整合 Elasticsearch,实现 function score query 权重分查询

运行环境:JDK 7 或 8,Maven 3.0+技术栈:SpringBoot 1.5+,ElasticSearch 2.3.2 本文提纲一.ES 的使用场景二.运行 springboot-elasticsearch 工程三.springboot-elasticsearch 工程代码详解 一.ES 的使用场景 简单说,ElasticSearch(简称 ES)是搜索引擎,是结构化数据的分布式搜索引擎.在<Elasticsearch 和插件 elasticsearch-head 安装详解>  和

SpringBoot整合ElasticSearch实现多版本的兼容

前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和SpringBoot进行结合使用. ElasticSearch介绍 ElasticSearch是一个基于Lucene的搜索服务器,其实就是对Lucene进行封装,提供了 REST API 的操作接口 ElasticSearch作为一个高度可拓展的开源全文搜索和分析引擎,可用于快速地对大数据进行存储,搜索和分析.

spring boot 2.0 整合 elasticsearch NoNodeAvailableException

原文地址:spring boot 2.0 整合 elasticsearch NoNodeAvailableException 原文说的有点问题,下面贴出我的配置: 码云项目地址:https://gitee.com/11230595/springboot-elasticsearch elasticsearch.yml cluster.name: my-applicationnetwork.host: 0.0.0.0 http.port: 9200transport.tcp.port: 9300tr

Spring Boot整合Elasticsearch

Spring Boot整合Elasticsearch Elasticsearch是一个全文搜索引擎,专门用于处理大型数据集.根据描述,自然而然使用它来存储和搜索应用程序日志.与Logstash和Kibana一起,它是强大的解决方案Elastic Stack的一部分,我之前的一些文章中已经对此进行了描述. 保留应用程序日志不是Elasticsearch的唯一使用场景.它通常用作应用程序的辅助数据库,是一个主关系数据库.如果您必须对大型数据集执行全文搜索或仅存储应用程序不再修改的许多历史记录,这个方

SpringBoot2.0之整合ElasticSearch

就类比数据库到时候去实现 服务器端配置 集群名字  与yml名字一致 pom: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/

Spring-boot2.0.1.BUILD-SNAPSHOT整合Elasticsearch报failed to load elasticsearch nodes错误解决办法

spring-boot整合es的application.properties的默认配置为: spring.data.elasticsearch.cluster-nodes=localhost:9200 将端口号改成9300即可解决failed to load elasticsearch nodes错误 拓展:如果es的安装版本为2.x,那么spring-boot对应的版本要大于1.4.0.RC1版本![结果来源于stackoverflow] p.p1 { margin: 0.0px 0.0px

spring-data-elasticsearch整合elasticsearch

花了一个晚上 整合最新版本的spring-data-elasticsearch与elasticsearch,遇到各种版本冲突 之类的问题,测试效果如图:

SpringBoot检索篇Ⅳ --- 整合ElasticSearch

知识储备:  关于ElasticSearch的基本使用我已经在上一篇文章介绍过了(传送门),本篇文章主要讲述的是SpringBoot与ElasticSearch的整合以及简单的使用. 原文地址:https://www.cnblogs.com/wangxiayun/p/10271122.html

Spring轻松整合ElasticSearch

完整项目代码地址(https://github.com/fonxian/spring-elasticsearch-example/tree/master/spring-elasticsearch-example) 一.整合过程 1.引入依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>