springboot整合elasticsearch常用的方式有以下三種
- 1,Java API
這種方式基於TCP和ES通信,官方已經明確表示在ES 7.0版本中將棄用TransportClient客戶端,且在8.0版本中完全移除它,所以不提倡。 - 2,REST Client
上面的方式1是基於TCP和ES通信的(而且TransPort將來會被拋棄……),官方也給出了基於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操作數據庫一樣方便。用過jpa的同學一定知道。
- jpa只需要簡單繼承JpaRepository就可以實現對數據庫表的crud操作
public interface UserRepository extends JpaRepository<UserBean, Long> {}
- spring-data-elasticsearch同樣,只要繼承ElasticsearchRepository就可以實現常見的es操作了。
public interface UserESRepository extends ElasticsearchRepository<UserBean, Long> {}
下面我們就來講解下springboot2繼承 spring-data-elasticsearch的具體步驟。
springboot版本 | Elasticsearch版本 |
---|---|
2.1.3.RELEASE | 6.4.3 |
一,首先是創建springboot項目
如上圖箭頭所指,springboot版本選2.1.3,然後添加web和elasticsearch倉庫
- 創建項目完成後,我們完整的pom.xml文件如下
<?xml version="1.0" encoding="UTF-8"?>
<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/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.qcl</groupId>
<artifactId>es</artifactId>
<version>0.0.1</version>
<name>es</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
spring-boot-starter-data-elasticsearch:就是我們所需要集成的es。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
二,下載elasticsearch本地版本
這裏下載本地elasticsearch,其實和我們下載本地mysql是一樣的,你要用elasticsearch肯定要下載一個本地版本用來存儲查詢數據啊。
下面來簡單的講解下elasticsearch版本的下載步驟
-
1,到官網
https://www.elastic.co/downloads/
選擇箭頭所指,點擊download
選擇你所對應的系統,這裏要注意,雖然官方最新版本是6.6.2,我們springboot項目裏使用的是6.4.3版本。這個沒有關係的,官方版本是向下兼容的。 -
2,下載成功後解壓,並進入到config文件夾下
進入config文件夾後,找到elasticsearch.yml
然後用下面這個文件替換elasticsearch.yml裏面的內容
# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
# Before you set out to tweak and tune the configuration, make sure you
# understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: my-application
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: 0.0.0.0
#
# Set a custom port for HTTP:
#
http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes:
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true
#qcl自己加的
http.cors.enabled: true
http.cors.allow-origin: "*"
node.master: true
node.data: true
這裏的cluster.name: my-application就代表我們的es的名稱叫my-application
- 3,啓動es
進入到bin文件
點擊elasticsearch腳本,即可啓動es,腳本運行完,在瀏覽器中輸入http://localhost:9200/
如果出現下面信息,就代表es啓動成功。
三,配置es
在創建的springboot項目下的application.yml做如下配置
#url相關配置,這裏配置url的基本url
server:
port: 8080
spring:
## Elasticsearch配置文件(必須)
## 該配置和Elasticsearch本地文件config下的elasticsearch.yml中的配置信息有關
data:
elasticsearch:
cluster-name: my-application
cluster-nodes: 127.0.0.1:9300
四,添加數據到es,並實現搜索
- 1,創建bean
我們像jpa那樣,創建es自己的bean,如下
package com.qcl.es;
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;
/**
* Created by qcl on 2018/7/10.
* ES相關
*/
@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;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
@Override
public String toString() {
return "UserES{" +
"userId=" + id +
", userName='" + userName + '\'' +
", userPhone='" + userPhone + '\'' +
'}';
}
}
- 2,創建操作數據的Repository
package com.qcl.es;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Created by qcl on 2019-03-23
* 微信:2501902696
* desc:
*/
public interface UserESRepository extends ElasticsearchRepository<UserES, Long> {}
- 3,創建controller
package com.qcl.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;
/**
* Created by qcl on 2019-03-23
* 微信:2501902696
* desc:
*/
@RestController
public class UserController {
@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;
}
}
啓動springboot項目
我們簡單的實現了
- 往es裏插入數據
- 查詢所有數據
- 根據搜索key,搜索信息
驗證
-
插入一個userName='李四'&userPhone='272501902696'的數據
http://localhost:8080/create?id=5&userName='李四'&userPhone='272501902696'
-
查詢上面的數據是否插入成功,可以看到李四這條數據已經成功插入。
-
搜索 userName包含'四'的信息,可以看到,成功感搜索到一條
-
搜索 userName包含'石'的信息,可以看到,成功感搜索到4條
到此我們就實現了springboot集成es的功能。後面我們再做複雜搜索就基於這個基礎上做對應的操作即可。
如果你有springboot相關的問題可以加我微信交流
2501902696(備註java)