- ElasticSearch和kibana安装(基于docker)
- Springboot整合ElasticSearch(demo测试)
- kibana配合操作查看
- Springboot整合ElasticSearch(整体)
ElasticSearch和kibana安装(基于docker)
一、创建Elasticsearch容器
(1) 先拉取Elasticsearch镜像(需要带上版本号,默认无法拉取
)
docker pull elasticsearch:7.14.2
(2)创建挂载目录并修改目录的权限
- 创建文件夹es-cluster
- 并创建es01 es02 es03三个子文件夹
- 分别在子文件夹下创建对应的data和plugins文件夹以及es.yml文件
es.yml配置中添加如下配置:
es01.yml 根据自己环境修改ip地址
cluster.name: elasticsearch-cluster
node.name: es-node1
network.bind_host: 0.0.0.0
network.publish_host: 127.0.0.1
http.port: 9200
transport.tcp.port: 9300
http.cors.enabled: true
http.cors.allow-origin: "*"
node.master: true
node.data: true
discovery.zen.ping.unicast.hosts: ["127.0.0.1:9300","127.0.0.1:9301","127.0.0.1:9302"]
discovery.zen.minimum_master_nodes: 2
(3)执行docker命令 创建运行容器
- 单节点运行:
docker run -d -e ES_JAVA_OPTS="-Xms512m -Xmx512m" -e "discovery.type=single-node" -p 9200:9200 -p 9300:9300 --name elasticsearch elasticsearch:7.14.2
- 集群运行:
docker run -e ES_JAVA_OPTS="-Xms512m -Xmx512m" -d -p 9200:9200 -p 9300:9300 -p 5601:5601 -v /Users/fuhanping/es-cluster/es01/es01.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /Users/fuhanping/es-cluster/es01/plugins1:/usr/share/elasticsearch/plugins -v /Users/fuhanping/es-cluster/es01/data:/usr/share/elasticsearch/data --name ES01 elasticsearch:7.14.2
docker run -e ES_JAVA_OPTS="-Xms512m -Xmx512m" -d -p 9200:9200 -p 9300:9300 -p 5601:5601 -v /Users/fuhanping/es-cluster/es01/es02.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /Users/fuhanping/es-cluster/es02/plugins1:/usr/share/elasticsearch/plugins -v /Users/fuhanping/es-cluster/es02/data:/usr/share/elasticsearch/data --name ES02 elasticsearch:7.14.2
docker run -e ES_JAVA_OPTS="-Xms512m -Xmx512m" -d -p 9200:9200 -p 9300:9300 -p 5601:5601 -v /Users/fuhanping/es-cluster/es01/es03.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /Users/fuhanping/es-cluster/es03/plugins1:/usr/share/elasticsearch/plugins -v /Users/fuhanping/es-cluster/es03/data:/usr/share/elasticsearch/data --name ES03 elasticsearch:7.14.2
(4)访问浏览器
http://localhost:9200
成功则显示以下内容:
二、创建kibana容器
(1) 拉取kibana镜像
docker pull kibana:7.14.1
(2)执行docker命令 创建运行容器
docker run --name kibana -e ELASTICSEARCH_HOSTS=http://192.168.4.165:9200 -p 5601:5601 -d kibana:7.14.1
若报错:"Unable to retrieve version information from Elasticsearch nodes.把指令中127.0.0.1替换为本机ip地址
(3)访问浏览器
http://localhost:5601
成功则显示以下内容:
Springboot整合ElasticSearch
一、pom.xml添加依赖
<!-- SpringBoot与elasticsearch整合的相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
二、定义配置类ElasticsearchConfig
package com.fhp.demo.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticsearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")
/** 多个节点也是在当前地方配置 */
// , new HttpHost("localhost", 9300, "http")
));
return client;
}
}
三、测试类ElasticsearchlTest(例举了一些基本方法)
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchlTest {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
public void test() throws IOException {
System.out.println("test");
}
/**
* 功能描述:createIndex 测试索引的创建 <br>
*
* @throws IOException
*/
@Test
public void createIndexTest() throws IOException {
// 1. 创建索引请求
CreateIndexRequest firstIndex = new CreateIndexRequest("fhp_index");
// 2. 客户端执行创建索引的请求
CreateIndexResponse response = restHighLevelClient.indices().create(firstIndex, RequestOptions.DEFAULT);
System.out.println(response);
}
/**
* 功能描述:existsIndexTest 判断索引是否存在 <br>
*
* @throws IOException
*/
@Test
public void existsIndexTest() throws IOException {
// 1. 创建一个get请求获取指定索引的信息
GetIndexRequest getIndexRequest = new GetIndexRequest("fhp_index");
// 2. 客户端执行请求判断索引是否存在
boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
System.out.println(exists);
if (!exists) {
System.out.println(">>>>>>>>> 索引不存在。。。。。");
return;
}
}
/**
* 功能描述:创建文档 <br>
*
* @throws IOException
*/
@Test
public void addDocumentTest() throws IOException {
// 1. 创建对象
User user = new User("fhp", 29);
// 2. 创建请求并指定索引
IndexRequest indexRequest = new IndexRequest("fhp_index");
// 3. 创建的规则:put /fhp_index/_doc/1
indexRequest.id("2"); // 设置ID
indexRequest.timeout("1s"); // 设置超时时间
// 4. 将数据放入到请求中
indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
// 5. 使用客户端发送请求
IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(index));
}
/**
* 功能描述:getDocumentTest 获取文档信息 <br>
*
* @throws IOException
*/
@Test
public void getDocumentTest() throws IOException {
// 1. 创建请求信息绑定索引和指定需要查询的文档id
GetRequest getRequest = new GetRequest("fhp_index", "2");
// GetRequest getRequest = new GetRequest("fhp_index");
// 设置不获取的返回时的_source的上下文,一般情况是不需要设置的
// getRequest.fetchSourceContext(new FetchSourceContext(false)).storedFields("_none_");
// 2. 判断指定的索引和id是否存在
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
if (!exists) {
System.out.println(">>>>>>>> 当前索引:fhp_index对应的id:1 不存在");
return;
}
System.out.println(">>>>>>>> 当前索引:fhp_index对应的id:1 存在");
// 3. 获取指定ID的资源信息
GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
// 4. 打印获取到的资源信息
System.out.println(response.getSourceAsString());
System.out.println(JSON.toJSONString(response));
}
/**
* 功能描述:searchTest 批量搜索,可以设置高亮等信息 <br>
*
* @throws IOException
*/
@Test
public void searchTest() throws IOException {
// 1. 创建批量搜索请求,并绑定索引
SearchRequest searchRequest = new SearchRequest("fhp_index");
// 2. 构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 【注意:这里有个坑,当中文查询时,如果使用ik分词器会查询不到数据,属性需要使用xxx.keyword才能查询到数据】
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", "姓名7"); // 设置精确查询
// QueryBuilders.matchAllQuery();
sourceBuilder.query(termQueryBuilder).timeout(new TimeValue(60, TimeUnit.SECONDS));
// 3. 将查询条件放入搜索请求request中
searchRequest.source(sourceBuilder);
// 4. 发起查询请求获取数据
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(response));
System.out.println(JSON.toJSONString(response.getHits().getHits()));
}
}
kibana配合操作查看
HEAD fhp_index //HEAD (索引值) -- 先判定fhp_index索引是否创建
GET fhp_index/_doc/1 //请求方式 索引值/_doc/{id} -- 查看id为1的文档
GET fhp_index/_doc/2
GET fhp_index/_doc/3
Springboot整合ElasticSearch(整体)
一、pom.xml添加依赖
<!-- SpringBoot与elasticsearch整合的相关依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
二、application.properties
# ELASTICSEARCH (ElasticsearchProperties)
# Elasticsearch cluster name.
spring.data.elasticsearch.cluster-name=elasticsearch
# Comma-separated list of cluster node addresses.
spring.data.elasticsearch.cluster-nodes=192.168.4.165:9200
# Whether to enable Elasticsearch repositories.
spring.data.elasticsearch.repositories.enabled=true
三、实体类
package com.fhp.demo.vo;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@Data
@Document(indexName = "fhp_index")
public class User {
@Id
private String id;
private String name;
private Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}
四、Repository类
/**
* 接口关系:
* ElasticsearchRepository --> ElasticsearchCrudRepository --> PagingAndSortingRepository --> CrudRepository
*/
public interface UserRepository extends ElasticsearchRepository<User, String> {
Optional<User> findById(String id);
}
五、service层
public interface UserService {
Optional<User> findById(String id);
}
六、实现类
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
@Qualifier("userRepository")
private UserRepository userRepository;
@Override
public Optional<User> findById(String id) {
//CrudRepository中的方法
return userRepository.findById(id);
}
@Override
public User save(User user) {
return userRepository.save(user);
}
}
七、控制器
@RestController
public class ElasticController {
@Autowired
private UserService userService;
@RequestMapping("/user/{id}")
@ResponseBody
public User getBookById(@PathVariable String id){
Optional<User> opt =userService.findById(id);
User user=opt.get();
System.out.println(user);
return user;
}
@RequestMapping("/save")
@ResponseBody
public void Save() {
User user = new User("傅安安",29);
System.out.println(user);
userService(user);
}
}