springboot整合elasticsearch常用的方式有以下三种

  • 1,Java API
    基于TCP和ES通信,官方已经明确表示在ES 7.0版本中将弃用TransportClient客户端,且在8.0版本中完全移除它,所以不提倡。
  • 2,REST Client
    基于HTTP的客户端REST Client(推荐使用),官方给出来的REST Client有Java Low Level REST Client和Java Hight Level REST Client两个,前者兼容所有版本的ES,后者是基于前者开发出来的,只暴露了部分API,待完善
  • 3,spring-data-elasticsearch
    Spring也提供了本身基于SpringData实现的一套方案spring-data-elasticsearch

采用spring-data-elasticsearch这种方式来集成es。由于spring为我们封装了常见的es操作。和使用jpa操作数据库一样方便。

只要继承ElasticsearchRepository就可以实现常见的es操作了

public interface UserRepository extends JpaRepository<UserBean, Long> {}

具体步骤如下:

1、创建项目

创建后的项目pom文件加入了es依赖

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

2、mac本地下载elasticsearch,采用brewhome(用过的都知道好)软件安装elasticsearch

brew install elasticsearch

安装后的信息如下:

elasticsearch:  /usr/local/Cellar/elasticsearch/6.8.2
Data:    /usr/local/var/elasticsearch/elasticsearch_xuchen/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_mengqingmei.log
Plugins: /usr/local/opt/elasticsearch/libexec/plugins/
Config:  /usr/local/etc/elasticsearch/
plugin script: /usr/local/opt/elasticsearch/libexec/bin/elasticsearch-plugin

启动elasticsearch

brew services start elasticsearch

浏览器访问http://localhost:9200/如果出现下面信息,就代表es启动成功。

3、在创建的springboot项目下的application.properties做如下配置

## Elasticsearch配置文件(必须)
## 该配置和Elasticsearch本地文件config下的elasticsearch.yml中的配置信息有关
spring.data.elasticsearch.cluster-name=elasticsearch_mengqingmei
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s
spring.data.elasticsearch.repositories.enabled=true
spring.data.elasticsearch.cluster-nodes=localhost:9300

4、实现创建搜索代码

(1)创建bean采用lombok减少getter、setter代码

package com.mqm501.es;

import lombok.Data;
import lombok.NoArgsConstructor;
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;

@NoArgsConstructor
@Data
@Document(indexName = "user", type = "docs", shards = 1, replicas = 0)
public class UserES {
  //主键自增长
  @Id
  private Long id;//主键

  //@Field(type = FieldType.Text, analyzer = "ik_max_word")
  private String userName;
  private String userPhone;

}

(2)创建操作数据的Repository

package com.mqm501.es;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface UserESRepository extends ElasticsearchRepository<UserES, Long> {}

(3)创建controller

package com.mqm501.es;

import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserESController {
  @Autowired
  private UserESRepository repositoryES;

  @GetMapping("/create")
  public String create(
      @RequestParam("id") Long id,
      @RequestParam("userName") String userName,
      @RequestParam("userPhone") String userPhone) {
    UserES userES = new UserES();
    userES.setId(id);
    userES.setUserName(userName);
    userES.setUserPhone(userPhone);
    return repositoryES.save(userES).toString();
  }

  private String names;

  @GetMapping("/get")
  public String get() {
    names = "";
    Iterable<UserES> userES = repositoryES.findAll();
    userES.forEach(userES1 -> {
      names += userES1.toString() + "\n";
    });
    return names;
  }

  private String searchs = "";

  @GetMapping("/search")
  public String search(@RequestParam("searchKey") String searchKey) {
    searchs = "";
    // 构建查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本分词查询
    queryBuilder.withQuery(QueryBuilders.matchQuery("userName", searchKey));
    // 搜索,获取结果
    Page<UserES> items = repositoryES.search(queryBuilder.build());
    // 总条数
    long total = items.getTotalElements();
    searchs += "总共数据数:" + total + "\n";
    items.forEach(userES -> {
      searchs += userES.toString() + "\n";
    });
    return searchs;
  }
}

5、启动项目验证

插入一个userName='李四'&userPhone='272501902696'的数据
http://localhost:8080/create?id=5&userName='李四'&userPhone='24324545232'

查询数据是否插入成功。

http://localhost:8080/get

搜索 userName包含'四'的数据

http://localhost:8080/search?searchKey="李"

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐