客户端初始化
1.引入依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
2.覆盖默认es版本
在父工程里面指定,因为父工程可以全部匹配,这里用老版本呢是因为新版本api变化太大,而且企业中多用老版本,所以使用老版本。
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<elasticsearch.version>7.12.1</elasticsearch.version>
</properties>
3.初始化RestHightClient
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
HttpHost.create("http://192.168.150.101:9200")
));
商品mapping映射
#商品索引库
PUT /hmall
{
"mappings": {
"properties": {
"id":{
"type": "keyword"
},
"name":{
"type": "text",
"analyzer": "ik_smart"
},
"price":{
"type": "integer"
},
"image":{
"type": "keyword",
"index": false
},
"category":{
"type": "keyword"
},
"brand":{
"type": "keyword"
},
"sold":{
"type": "integer"
},
"commentCount":{
"type": "integer",
"index":false
},
"isAD":{
"type": "boolean"
},
"updateTime":{
"type": "date"
}
}
}
}
索引库操作
public class ElasticTest {
private RestHighLevelClient client;
@Test
void CreatIndex() throws IOException {
//准备Request对象
CreateIndexRequest request = new CreateIndexRequest("items");
//准备请求参数
request.source(Mapping, XContentType.JSON);
//发送请求
client.indices().create(request, RequestOptions.DEFAULT);
}
@Test
void GetIndex() throws IOException {
//创建对象
GetIndexRequest request = new GetIndexRequest("items");
boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);
System.out.println("exists = "+exists);
}
@Test
void DeleteIndex() throws IOException {
//创建对象
DeleteIndexRequest request = new DeleteIndexRequest("items");
client.indices().delete(request,RequestOptions.DEFAULT);
}
@BeforeEach
void setUp(){
client = new RestHighLevelClient(RestClient.builder(
HttpHost.create(&#