Elasticsearch安装
docker 安装(Elasticsearch安装需要的内存在2G以上)
1,下载镜像:docker pull elasticsearch:7.13.2
2,运行容器:docker run -d -p 9200:9200 -p 9300:9300 —name elasticsearch-7.13.2 elasticsearch:7.13.2
进入容器:docker exec -it elasticsearch-7.13.2 /bin/bash
安装 ik 分词器:./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.13.2/elasticsearch-analysis-ik-7.13.2.zip
修改 es 配置文件:`vi ./config/elasticsearch.yml
cluster.name: "docker-cluster"
network.host: 0.0.0.0
# minimum_master_nodes need to be explicitly set when bound on a public IP
# set to 1 to allow single node clusters
# Details: https://github.com/elastic/elasticsearch/pull/17288
discovery.zen.minimum_master_nodes: 1
# just for elasticsearch-head plugin
http.cors.enabled: true
http.cors.allow-origin: "*"
退出容器:exit
停止容器:docker stop elasticsearch-7.13.2
启动容器:docker start elasticsearch-7.13.2
Elasticsearch介绍
ElasticSearch 官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/6.x/getting-started.html
spring-data-elasticsearch 官方文档:https://docs.spring.io/spring-data/elasticsearch/docs/3.1.2.RELEASE/reference/html/
Elasticsearch是一个开源的分布式、RESTful 风格的搜索和数据分析引擎,它的底层是开源库Apache Lucene。
Elasticsearch使用
引入依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<!-- 修改elasticsearch的版本 -->
<elasticsearch.version>7.6.2</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- spring-boot-starter-data-elasticsearch的依赖中已经引入了当前依赖,因此只需要修改相关的版本即可
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
添加配置application.yml
spring:
es:
url: 127.0.0.1
scheme: http
port: 9200
index: person_index
本文使用SpringBoot结合RestHighLevelClient来讲解高级客户端的使用。
配置文件写好后,使用使用一个ElasticSearchConfig实例化创建一个RestHighLevelClient的Bean实例,使用注解将配置文件的值注入到类中,创建RestHighLevelClient对象时可以看到,内部其实是创建了一个低级的客户端RestClient来实现,传入ElasticSearch的服务器地址和端口号。
@Configuration
public class EsClientConfig {
@Value("${spring.es.url}")
private String url;
@Value("${spring.es.scheme}")
private String scheme;
@Value("${spring.es.port}")
private Integer port;
@Bean
public RestHighLevelClient highLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(url, port, scheme)));
return client;
}
}
引用RestHighLevelClient对象
在需要用到ElasticSearch的类中注入索引名字、类型名字和高级客户端对象。