一、环境准备-ElasticSearch和Kibana
elasticsearch7.16.2官方下载地址:https://www.elastic.co/cn/downloads/past-releases/elasticsearch-7-16-2
kibana7.16.2官方下载地址:https://www.elastic.co/cn/downloads/past-releases/kibana-7-16-2
1.windows系统选择下载windows-x86_64.zip后解压,先双击bin\elasticsearch.bat运行elasticsearch
2.等待访问localhost:9200成功后,再双击bin\kibana.bat运行kibana,访问localhost:5601查看是否运行成功。
二、SpringBoot(版本2.6.3)项目加入依赖
1.指定jakarta.json为最新版本
<properties>
<java.version>1.8</java.version>
<!-- 如果报错:java.lang.NoClassDefFoundError: jakarta/json/JsonException,是因为Java Api Client依赖1.1.6版本的jakarta.json,指定版本为2.0.1即可-->
<jakarta-json.version>2.0.1</jakarta-json.version>
</properties>
2.加入Java API Client (Elasticsearch)和jackson (JSON)依赖
目前,最新版本为4.3.2的Spring Data Elasticsearch (SpringBoot2.6.2通过spring-data 9300端口TCP方式操作Elasticsearch)只支持到Elasticsearch7.15.2版本为止,elasticsearch-rest-high-level-client也已经在7.15.0弃用,因此7.16及以上版本可以改为使用Java API Client。
<!-- Elasticsearch Java API Client
https://mvnrepository.com/artifact/co.elastic.clients/elasticsearch-java -->
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>7.16.2</version>
</dependency>
<!-- 为Elasticsearch引入的Json依赖
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
三、编写测试类运行(在已经启动elasticsearch.bat的前提下)
编写了创建单个索引,创建单个文档,批处理创建多个文档,查询索引,按条件过滤范围查询等方法,测试成功。
package com.zhy.springboot;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Zhu HongYi
* @version 1.0
* @Date: 2022/03/07/21:37
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootLearnApplication.class)
public class ElasticSearchTest {
static JacksonJsonpMapper jacksonJsonpMapper=new JacksonJsonpMapper();//json映射器
ElasticsearchTransport transport;
ElasticsearchClient client;
String index="products";
@Before
public void startup(){
RestClient restClient=RestClient.builder(new HttpHost("localhost",9200)).build();
transport=new RestClientTransport(restClient,jacksonJsonpMapper);//创建传输层
client=new ElasticsearchClient(transport);
}
@After
public void after() throws IOException {
transport.close();
System.out.println("关闭传输层成功");
}
@Test
public void createIndex() throws IOException {//创建索引
CreateIndexResponse createIndexResponse=
client.indices().create(new CreateIndexRequest.Builder().index(index).build());
// client.indices().create(c->c.index(index));//lambda写法
System.out.println("创建索引操作测试:"+createIndexResponse.acknowledged());
}
@Test
public void createDocument() throws IOException {//创建单个文档(map类型) request [PUT http://localhost:9200/products/_doc/1/_create]
Map<String,String> map=new HashMap<>();
map.put("name","product 0");
map.put("price",String.valueOf(50+(int)(Math.random()*500)));
CreateResponse createResponse=
client.create(CreateRequest.of(c->c.index(index).id("1").type("_doc").document(map)));//id已存在则会创建失败
System.out.println("创建单个文档测试:"+createResponse.result().jsonValue());
}
@Test
public void bulkCreateDocuments() throws IOException {//批处理创建多个文档
List<BulkOperation> list=new ArrayList<>();
for(int i=10;i<20;i++){
Map<String,String> map=new HashMap<>();
map.put("name","product "+i);
map.put("price",String.valueOf(50+(int)(Math.random()*500)));
int id=i;
list.add(BulkOperation.of(c->c.create(e->e.index(index).id(String.valueOf(id)).document(map))));
}
BulkResponse bulkResponse=
client.bulk(new BulkRequest.Builder().index(index).operations(list).build());//.type("_doc")加不加都可以
System.out.println("批量创建多个文档测试:(例:查看第一个文档创建结果)"+bulkResponse.items().get(0).result());//created
}
@Test
public void searchIndex() throws IOException {//查询索引 request [POST http://localhost:9200/products/_search?typed_keys=true]
SearchResponse<Object> searchResponse=client.search(new SearchRequest.Builder().index(index).build(),Object.class);
List<Hit<Object>> list=searchResponse.hits().hits();
List<Object> result=new ArrayList<>();
for(Hit<Object> hit:list){
result.add(hit.source());
}
System.out.println(result);//[{price=206, name=product 0}, {price=548, name=product 5},...]
}
@Test
public void searchInRangeOfPrice() throws IOException {//从products索引中搜索价格字段值>=300&&<=500的文档
SearchResponse<Object> searchResponse=
client.search(
s->s.index(index).query(
c->c.bool(
b->b.filter(
q->q.range(
v->v.field("price").gte(JsonData.of("300")).lte(JsonData.of("500"))))))
,Object.class);
List<Hit<Object>> list=searchResponse.hits().hits();
List<Object> result=new ArrayList<>();
for(Hit<Object> hit:list){
result.add(hit.source());
}
System.out.println(result);//[{price=396, name=product 6}, {price=483, name=product 8}, {price=393, name=product 9}, ...]
}
@Test
public void deleteDocument() throws IOException {//删除 request [DELETE http://localhost:9200/products/_doc/1]
System.out.println("查看删除是否成功:"+client.delete(d->d.index(index).id("1")).result().jsonValue());//deleted
}
}
四、在Kibana中查看创建的索引及其内容
1.可以通过Get请求查询索引内容localhost:9200/products/
2.还可以通过Kibana创建索引模式匹配想要查看的索引,从而提供对索引的可视化管理。
http://localhost:5601/app/management/kibana/indexPatterns
点击Management-Stack Management-Index patterns-Create index pattern输入自己创建的索引名称(比如products),即可在index pattern处查看索引的字段,在Analytics-Discover里
选择已创建的索引模式查看其中的文档。

本文介绍了如何在Windows环境下安装ElasticSearch7.16.2和Kibana7.16.2,以及如何在SpringBoot2.6.3项目中配置和使用Java API Client进行数据操作。文章详细讲解了从添加依赖、启动服务,到编写测试类实现索引和文档的创建、查询,最后在Kibana中查看和管理索引内容的过程。
3510

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



