Elasticsearch 8.2.2安装,配置及简单应用
系统环境
OS:centos7
安装Elasticsearch
下载
https://www.elastic.co/cn/downloads/elasticsearch
此处下载版本8.2.2
ES 8.x版本内置jdk,不依赖JAVA环境变量,如果需要使用本地JAVA环境可以定义ES_JAVA_HOME变量或者在ES安装目录下bin/elasticsearch-env文件中指定。,不过需要1.8及以上的JDK。
安装配置
解压缩并copy到/user/local目录
1. tar -xzvf elasticsearch-8.2.2
2. mv elasticsearch-8.2.2 /usr/local/
编辑config/elasticsearch.yml文件,放开network.host并修改为0.0.0.0,确保在服务启动之后可在其他主机访问ES服务。
配置用户
Elasticsearch服务不能以系统root用户身份启动,需要配置其他用户
groupadd esuser
useradd -g esuser esuser
chown -R esuser:esuser /usr/local/elasticsearch-8.2.2/
服务配置
此时如启动服务,将会报如下三个错误信息:
ERROR: [3] bootstrap checks failed. You must address the points described in the following [3] lines before starting Elasticsearch.
bootstrap check failure [1] of [3]: max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
bootstrap check failure [2] of [3]: max number of threads [3818] for user [esuser] is too low, increase to at least [4096]
bootstrap check failure [3] of [3]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
ERROR: Elasticsearch did not exit normally - check the logs at /usr/local/elasticsearch-8.2.2/logs/elasticsearch.log
解决以上的启动异常,调整如下系统配置:
- ElasticSearch进程的最大文件描述大小至少需65535,修改配置文件 /etc/security/limits.conf,添加如下内容:
* soft nofile 65535
* hard nofile 65535
- 最大线程数至少需要4096,在刚才的配置文件刚才的位置添加如下内容:
* soft nproc 4096
* hard nproc 4096
针对1,2的以上配要生效的话也许需要用户重新登录或重启系统。
- 系统虚拟内存默认最大映射数至少262144,修改配置文件 /etc/sysctl.conf,在文件末尾添加(或修改)如下内容:
vm.max_map_count=262144
执行如下命令使其生效
sysctl -p
继续编辑配置文件 config/elasticsearch.yml,添加如下内容
ingest.geoip.downloader.enabled: false
否则,启动服务时报如下错误信息:
[2022-09-30T16:45:13,884][ERROR][o.e.i.g.GeoIpDownloader ] [localhost.localdomain] exception during geoip databases update
java.net.SocketTimeoutException: Connect timed out
at sun.nio.ch.NioSocketImpl.timedFinishConnect(NioSocketImpl.java:543) ~[?:?]
ES试图更新地图数据库,目前可以先禁掉,用时再说。
启动服务(切换至/bin目录),先使用如下命令看服务是否正常启动
./elasticsearch
一般情况,需要Elasticsearch在后台运行,执行如下命令
./elasticsearch -d
启动服务成功,控制台中显示了一些重要信息:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Elasticsearch security features have been automatically configured!
✅ Authentication is enabled and cluster connections are encrypted.
ℹ️ Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
5m7XIY7EcopbKqdruXT2
ℹ️ HTTP CA certificate SHA-256 fingerprint:
9b6d95393b9f5d4c598f5b91df0adcccb7afd9dec4177a4decc6db0268afec35
ℹ️ Configure Kibana to use this cluster:
• Run Kibana and click the configuration link in the terminal when Kibana starts.
• Copy the following enrollment token and paste it into Kibana in your browser (valid for the next 30 minutes):
eyJ2ZXIiOiI4LjIuMiIsImFkciI6WyIxOTIuMTY4LjE3NC4xMDI6OTIwMCJdLCJmZ3IiOiI5YjZkOTUzOTNiOWY1ZDRjNTk4ZjViOTFkZjBhZGNjY2I3YWZkOWRlYzQxNzdhNGRlY2M2ZGIwMjY4YWZlYzM1Iiwia2V5IjoiZVBtTG5vTUJxYnlLQV91QlNZcVE6ekVhZS1wdzdSOS1yekgxVG1FeTV3USJ9
ℹ️ Configure other nodes to join this cluster:
• Copy the following enrollment token and start new Elasticsearch nodes with `bin/elasticsearch --enrollment-token <token>` (valid for the next 30 minutes):
eyJ2ZXIiOiI4LjIuMiIsImFkciI6WyIxOTIuMTY4LjE3NC4xMDI6OTIwMCJdLCJmZ3IiOiI5YjZkOTUzOTNiOWY1ZDRjNTk4ZjViOTFkZjBhZGNjY2I3YWZkOWRlYzQxNzdhNGRlY2M2ZGIwMjY4YWZlYzM1Iiwia2V5IjoiZHZtTG5vTUJxYnlLQV91QlNZcDg6ZTJHUVlhY2FUaC1nYl9tblpQTVJvdyJ9
If you're running in Docker, copy the enrollment token and run:
`docker run -e "ENROLLMENT_TOKEN=<token>" docker.elastic.co/elasticsearch/elasticsearch:8.2.2`
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
把这些信息保存起来,远程登录或Kibana配置时需要用到,不过,到时候可以重置获取。
登录远程服务
有防火墙的话,首先开放9200端口:
firewall-cmd --zone=public --add-port=9200/tcp --permanent
firewall-cmd --reload
访问如下url:
https://ip:9200/ (注:是https,不是http)
要求输入用户名密码(前面保存的初次启动时显示的配置信息:elastic/)
可以运行如下命令来手动设置各用户的密码
./bin/elasticsearch-setup-passwords interactive
或者设置指定用户的密码
./bin/elasticsearch-reset-password --username elastic -i
登录后显示如下信息,说明系统成功启动并可访问
{
"name" : "localhost.localdomain",
"cluster_name" : "elasticsearch",
"cluster_uuid" : "uPCMas0jQ9mC7s4gU8pdng",
"version" : {
"number" : "8.2.2",
"build_flavor" : "default",
"build_type" : "tar",
"build_hash" : "9876968ef3c745186b94fdabd4483e01499224ef",
"build_date" : "2022-05-25T15:47:06.259735307Z",
"build_snapshot" : false,
"lucene_version" : "9.1.0",
"minimum_wire_compatibility_version" : "7.17.0",
"minimum_index_compatibility_version" : "7.0.0"
},
"tagline" : "You Know, for Search"
}
此处进一步探讨一个问题,学习时,在本地单机测试环境可能并不需要https、用户名密码、集群间身份验证,各种证书,令牌等,而只通过访问http://ip:9200的方式访问。
可以调整一下配置,修改配置文件config/elasticsearch.yml,找到如下信息内容(这部分信息是刚才启动时,基于https由es自动添加进来的)

把那4个true,改为false即可,访问http://ip:9200 ,就可以直接访问了,至此,从开发的角度已经可以使用了
安装配置Kibana
Kibana是一个开源的分析与可视化平台,用于和ES一起使用的。可以用kibana搜索、查看ES中的数据。Kibana以图表、表格、地图等,直观的展示ES中的数据。
下载
https://www.elastic.co/cn/downloads/kibana
注意与elasticsearch的版本匹配。
安装
解压缩并copy到/user/local目录
基本配置
修改配置文件:config/kibana.yml
- 服务端口
server.port默认是5601 - 允许远程访问的地址
server.host默认为本机,如果允许Kibana服务供远程主机访问,需要在这个配置中填写远程主机的ip地址,如果不限远程主机,改为:0.0.0.0
启动
./bin/kibana
启动kibana服务,不允许root用户启动(记得6.x的时候是可以的),可以改用上文中的esuser用户启动(需首先修改esuser对kibana目录及文件的权限),或者携带启动参数 --allow-root 使用root用户启动

根据url访问kibana服务(当然ip地址不是0.0.0.0),按照提示完成对于elasticsearch的配置即可
首先输入elastic启动中的令牌(token),如果token没有记下来或者已经失效,可以用这个命令重新获取
./bin/elasticsearch-create-enrollment-token --scope kibana
注意:登录时使用的用户是elastic
OK!!!现在可以对ES的索引库进行一些实操训练了

安装配置分词器(IK)
Elasticsearch默认分词器不支持中文,此处安装一个常用的IK分词器。
分词类型(下文应用中指定示例)
ik_max_word 对文本做最细 力度的拆分
ik_smart 对文本做最粗粒度的拆分,这个其实基本够用
- 下载
https://github.com/medcl/elasticsearch-analysis-ik/releases
注意与elasticsearch的版本匹配。 - 在easticsearch的plugins目录下创建名为 analyser_ik 的目录,将下载好的zip包解压在该目录下。
- 执行elasticsearch-plugin list 即可查看到该插件,重启elasticsearch服务。
在kibana终端查看分词效果:
GET _analyze
{
"analyzer": "ik_smart",
"text": "测试一下搜索苹果手机怎么样呢"
}
基本应用
考虑一个基本场景,也是目前很多电商平台的基本应用场景,用户在平台输入关键词搜索商品,系统展示匹配的商品列表,如果依靠RDBMS来实现,即便很多RDBMS提供了全文检索功能,但实现时还是比较吃力,对于数据库的压力当然也很大,这时ES作为搜索引擎就可以发挥它的优势(此处只是几个简单的示例)。
以下操作在kibana中完成
索引库管理
查询索引库列表
GET /_cat/indices?v
创建索引
PUT /index_product
{
"mappings": {
"properties": {
"sname":{
"type": "text",
"analyzer": "ik_smart"
},
"surl":{
"type": "keyword",
"index": "false"
},
"price":{
"type": "float",
"index": "false"
},
"count":{
"type": "integer",
"index": "false"
},
"sdesc":{
"type": "text",
"analyzer": "ik_smart"
},
"ddate":{
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
}
}
}
}
mapping是对索引库中文档的约束,常见的mapping属性包括:
- type:字段数据类型,常见的简单类型有:
字符串:text(分词匹配),keyword(精确匹配,例如:品牌、国家、ip地址、email等)
数值:long、integer、short、byte、double、float
布尔:boolean
日期:date
对象:object - index:是否创建索引并参与搜索,默认为true
- analyzer:使用哪种分词器
- properties:该字段的子字段
查看索引
GET /index_product
修改索引
索引库一旦创建,无法修改mapping中已有的字段,但是却允许添加新的字段到mapping中,因为不会对倒排索引产生影响,这种方式相当于创建索引时不定义mapping,之后单独定义mapping。
PUT /index_product/_mapping
{
"properties": {
"sname":{
"type": "text",
"analyzer": "ik_smart"
},
"surl":{
"type": "keyword",
"index": "false"
},
"price":{
"type": "float",
"index": "false"
},
"count":{
"type": "integer",
"index": "false"
},
"sdesc":{
"type": "text",
"analyzer": "ik_smart"
}
}
}
查看映射
GET /index_product/_mapping
删除索引
DELETE /index_product
文档管理
创建文档
POST /index_product/_doc/product_1
{
"sname": "烟台苹果水果",
"surl": "http://product1.jpg",
"price": "10.0",
"count": "10",
"sdesc": "山东烟台苹果,产地:烟台,山东特产"
}
多创建几个不同的DOC文档
查询文档
GET /index_product/_doc/product_1
GET /index_product/_search?q=sname:水果
POST index_product/_search
{
"query": {
"match_all": {}
}
}
POST /index_product/_search
{
"query": {
"match": {
"sdesc": "随便搜索北京特产"
}
}
}
POST /index_product/_search
{
"query": {
"multi_match": {
"query": "水果",
"fields": ["sname","sdesc"]
}
}
}
以上是几种不同的查询方式,查询结果表明,分词搜索已经生效,万里长征第一步。
修改文档
修改文档分为:全量修改、增量修改
全量修改与新增文档相同,只是ES内部实现逻辑的问题;
增量修改即改变文档的部分字段值,DSL如下:
POST /index_product/_update/product_2
{
"doc": {
"sname": "莱阳梨水果",
"sdesc": "山东莱阳梨,产地:莱阳,山东特产"
}
}
删除文档
DELETE /index_product/_doc/product_2
至此,已经完成了ES单机应用的服务配置,下面我们看一下ES集群的配置
Elasticsearch集群配置
此处使用三台服务器配置ES集群,建议根据上文的配置步骤重新配置安装Elasticsearch,基本配置完成后先不要运行,继续完成集群配置。
以下的集群配置可在其中一台服务器上进行(在elasticsearch目录先以esuser用户执行命令),配置完成之后copy到其他服务器即可。
生成ca证书:
./bin/elasticsearch-certutil ca
默认ca文件名为elastic-stack-ca.p12即可,设置ca密码12345678;
生成节点通信证书
./bin/elasticsearch-certutil cert --ca elastic-stack-ca.p12
要求输入ca证书密码,证书文件名默认为elastic-certificates.p12即可,两次输入通信证书密码12345678(可以与ca证书密码不同);
此两个证书文件将生成到当前目录下,copy到config/certs目录下。
设置节点通信密码
./bin/elasticsearch-keystore add xpack.security.transport.ssl.keystore.secure_password
./bin/elasticsearch-keystore add xpack.security.transport.ssl.truststore.secure_password
通信证书密码设置为12345678,与之前的证书密码保持一致,此时将在config目录下生成elasticsearch-keystore文件。
# 查看keystore中的信息
./bin/elasticsearch-keystore list
签发https证书
./bin/elasticsearch-certutil http
这个操作的步骤好像有点多,不过注意几个关键环节,其他可以直接取默认值回车或视情况输入n跳过即可
- 输入certs/elastic-stack-ca.p12的路径
- 输入三个节点的hostname
- 输入三个节点的ip地址






命令执行成功在es主目录下生成elasticsearch-ssl-http.zip压缩文件,解压缩找到elasticsearch目录下的 http.p12文件,copy到certs目录下,另外还有kibana目录下有一个配置文件elasticsearch-ca.pem,copy到kibana/confiig目录下。
将刚才配置的私钥的密码添加到 es中的安全设置中
./bin/elasticsearch-keystore add xpack.security.http.ssl.keystore.secure_password
./bin/elasticsearch-keystore add xpack.security.http.ssl.truststore.secure_password
配置elasticsearch.yml
修改配置文件Elasticsearch.yml中如下配置信息:
cluster.name: my-application #集群名称
node.name: node-1 #节点名称
node.roles: [master,data] # master选举资格(至少两个)
network.host: 0.0.0.0#允许连接IP
http.port: 9200 # 访问端口
http.cors.enabled: true #是否支持跨域,默认为false
http.cors.allow-origin: “*” #当设置允许跨域,默认为 *,支持所有域名
discovery.seed_hosts: [“192.168.174.101:9300”, “192.168.174.102:9300”,“192.168.174.103:9300”] #集群成员
cluster.initial_master_nodes: [“node-1”, “node-2”, “node-3”]
配置文件中添加如下证书配置信息:
xpack.security.enabled: true
xpack.security.enrollment.enabled: true
xpack.security.http.ssl:
enabled: true
keystore.path: certs/http.p12
truststore.path: certs/http.p12
xpack.security.transport.ssl:
enabled: true
verification_mode: certificate
keystore.path: certs/elastic-certificates.p12
truststore.path: certs/elastic-certificates.p12
配置其他节点
拷贝
- elasticsearch-yml文件
- elasticsearch-keystore文件
- certs目录
到其他节点服务器相应位置(注意文件权限属性的调整),并修改elasticsearch.yml中节点名称。
如果一切正常,此时集群即配置完成。
启动集群
启动各节点elasticsearch服务,成功后,执行如下命令设置节点登录密码:
./bin/elasticsearch-reset-password --username elastic -i
配置Kibana
kibana不能使用elastic用户访问elastic服务,需要在elastic中为kibana用户设置密码,输入或由系统生成。
./bin/elasticsearch-reset-password -u kibana -i
在elastic中为kibana生成证书
./bin/elasticsearch-certutil csr -name kibana
此命令在ES目录下生成文件:csr-bundle.zip,解压缩后找到这两个文件:kibana.csr,kibana.key,移至kibana/config目录下,并在目录下执行下面的命令生成文件认证文件kibana.crt。:
openssl x509 -req -in kibana.csr -signkey kibana.key -out kibana.crt
配置kibana.yml,内容如下(下面的配置项在配置文件中都有,找到直接编辑):
server.ssl.enabled: true
server.ssl.certificate: config/kibana.crt
server.ssl.key: config/kibana.key
elasticsearch.hosts: ["https://192.168.174.101:9200"]
elasticsearch.username: "kibana" #es中创建的用户名
elasticsearch.password: "kibana" #用户密码
elasticsearch.ssl.certificateAuthorities: [ "config/elasticsearch-ca.pem" ] #https自签证书时生成的文件,也拷贝至此
到这儿,kibana针对es集群也配置完成,启动服务访问
https://ip:5601 试试吧,注意访问Kibana服务时的登录用户是elastic用户,而不是上面创建的kibana用户。
整合SpringBoot
获取证书和私钥
在config/certs目录下执行如下命令,从elastic-stack-ca.p12证书中获取crt证书,这是整合SpringBoot时需要用到的,elastic-stack-ca.p12是前面配置集群时生成的CA证书。
openssl pkcs12 -in elastic-stack-ca.p12 -nokeys -out ca.crt
从elastic-stack-ca.p12证书中获取key私钥(整合时不需要,仅在此记录)
openssl pkcs12 -in elastic-stack-ca.p12 -nocerts -nodes -out ca.key
在SpringBoot项目resource下创建certs目录,把cat.crt证书copy至此
maven依赖配置
从ES 7.15.0 开始官方已弃用elasticsearch-rest-high-level-client,因此不推荐使用 REST 客户端;
考虑到ES的版本升级太快,也不推荐spring-boot-starter-data-elasticsearch,它的更新速度完全跟不上ES的版本迭代速度,而且对于ES的高级特性支持也不友好;
ES官方推荐使用 Elasticsearch Java API客户端
一下是pom.xml配置中需要添加的依赖(非全部)
<repositories>
<!-- add the elasticsearch repo -->
<repository>
<id>elasticsearch-releases</id>
<url>https://artifacts.elastic.co/maven</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.json</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.2.2</version>
</dependency>
</dependencies>
配置文件application.yml
在配置文件中添加如下内容
elasticsearch:
hosts: 192.168.174.101:9200,192.168.174.102:9200
username: elastic
password: elastic
JAVA配置类
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.extern.slf4j.Slf4j;
@Configuration
@Slf4j
public class ElasticsearchConfig {
@Value("${elasticsearch.hosts}")
private String hosts;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Bean
public ElasticsearchClient ESClient() throws Exception {
ElasticsearchTransport transport = getElasticsearchTransport(username, password, getHosts());
return new ElasticsearchClient(transport);
}
/**
* 解析hosts字符串,转为HttpHost对象数组
*/
private HttpHost[] getHosts() {
if (!StringUtils.hasLength(hosts)) {
throw new RuntimeException("invalid elasticsearch configuration");
}
String[] hostArray = hosts.split(",");
HttpHost[] httpHosts = new HttpHost[hostArray.length];
HttpHost httpHost;
for (int i = 0; i < hostArray.length; i++) {
String[] strings = hostArray[i].split(":");
httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "https");
httpHosts[i] = httpHost;
}
return httpHosts;
}
private static SSLContext buildSSLContext() {
ClassPathResource resource = new ClassPathResource("certs/ca.crt");
SSLContext sslContext = null;
try {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate trustedca;
try (InputStream is = resource.getInputStream()) {
trustedca = factory.generateCertificate(is);
}
KeyStore trustStore = KeyStore.getInstance("pkcs12");
trustStore.load(null, null);
trustStore.setCertificateEntry("ca", trustedca);
SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);
sslContext = sslContextBuilder.build();
} catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
log.error("elasticsearch认证失败", e);
}
return sslContext;
}
private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost...hosts) {
//配置账号密码
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, passwd));
//设置自签证书
HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder
.setSSLContext(buildSSLContext())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.setDefaultCredentialsProvider(credentialsProvider);
//创建RestClient
RestClient client = RestClient
.builder(hosts)
.setHttpClientConfigCallback(callback)
.build();
return new RestClientTransport(client, new JacksonJsonpMapper());
}
}
到这儿,其实后面的内容已经不关键了,具体对ES的操作网上一搜一堆,但是,针对ES8的集群与SpringBoot的整合,因为模拟生产环境,涉及SSL证书等,反而比较少,配置到这儿关键问题已经基本解决。
如果感兴趣可以继续往下看,只是一点ES应用的皮毛,更高级的应用再继续搜索学习吧
doc映射类
此处使用上文用到的product
import java.util.Date;
public class Product {
String uid;
String sname;
int count;
double price;
String surl;
String sdesc;
Date ddate;
public Product() {
}
public Product(String uid, String sname, int count, double price, String surl, String sdesc) {
super();
this.uid = uid;
this.sname = sname;
this.count = count;
this.price = price;
this.surl = surl;
this.sdesc = sdesc;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getSurl() {
return surl;
}
public void setSurl(String surl) {
this.surl = surl;
}
public String getSdesc() {
return sdesc;
}
public void setSdesc(String sdesc) {
this.sdesc = sdesc;
}
public Date getDdate() {
return ddate;
}
public void setDdate(Date ddate) {
this.ddate = ddate;
}
}
服务类
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import org.springframework.stereotype.Service;
import com.skt.bus.es.dto.Product;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
@Service
public class ESService {
@Resource(name="ESClient")
private ElasticsearchClient elasticsearchClient;
//创建索引
public void addIndex(String name) throws IOException {
elasticsearchClient.indices().create(c -> c.index(name));
}
//判断索引是否存在
public boolean indexExists(String name) throws IOException {
return elasticsearchClient.indices().exists(b -> b.index(name)).value();
}
//删除索引
public void delIndex(String name) throws IOException {
elasticsearchClient.indices().delete(d -> d.index(name));
}
//查询索引
public void searchIndex(String name) throws IOException {
GetIndexResponse res = elasticsearchClient.indices().get(e -> e.index(name));
System.out.println(res.result());
}
//创建product doc
public void addIndex(Product product) throws IOException {
//method 1
IndexRequest<Object> indexRequest = new IndexRequest.Builder<>()
.index("index_product")
.id(product.getUid())
.document(product)
.build();
elasticsearchClient.index(indexRequest);
//method 2
elasticsearchClient.index(builder -> builder
.index("index_product")
.id(product.getUid())
.document(product)
);
}
//模糊搜索product doc
public void searchMultiMatch(String key) throws IOException {
SearchResponse<Product> r = elasticsearchClient.search(s -> s
.index("index_product")
.query(q -> q
.multiMatch(m -> m
.query(key)
.fields("sname","sdesc")
)
),
Product.class
);
List<Hit<Product>> hits = r.hits().hits();
for (Hit<Product> hit: hits) {
Product product2 = hit.source();
System.out.println("product " + product2.getUid() + ", score " + hit.score());
}
}
}
SpringBoot测试类
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.skt.bus.es.dto.Product;
import com.skt.bus.es.service.ESService;
@SpringBootTest
class TstsocketApplicationTests {
@Autowired
ESService esService;
@Test
void contextLoads() throws Exception {
try {
esService.searchMultiMatch("特产");
}
catch (Exception e) {
e.printStackTrace();
}
}
void addProduct() throws Exception {
Product p = new Product();
p.setUid("pid");
p.setCount(11);
p.setPrice(11.11);
p.setSurl("kaoya.jpb");
p.setSname("全聚德烤鸭");
p.setSdesc("北京特产,烤鸭,全聚德");
esService.addIndex(p);
}
void addIndex() throws Exception {
String indexName = "index_test";
try {
Assertions.assertFalse(esService.indexExists(indexName));
esService.addIndex(indexName);
Assertions.assertTrue(esService.indexExists(indexName));
esService.delIndex(indexName);
Assertions.assertFalse(esService.indexExists(indexName));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
到此为止,本文对于ES 8.x的单机环境配置应用,集群配置应用,SpringBoot集成,Kibana配置应用做了一个简单的示例,同时也作为个人记录备查,希望能对有需要的同学有点帮助。
在此多谢网上各位大侠的帖文,一边学习一边根据本人对特定业务场景进行应用分析,文中内容如有冒犯之处,请指出,本人加以更改;另外,文中如有错漏之处,还请各位大侠指正,谢谢!
如转载请注明出处!
2万+




被折叠的 条评论
为什么被折叠?



