创建一个maven项目
项目结构
1.1在maven中添加引用
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>ElasticSearch</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<parent>
<artifactId>spring-boot-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.2.5.RELEASE</version>
</parent>
<dependencies>
<!-- springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- log4j2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<!-- ElasticSearch-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.13.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.13.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.13.1</version>
</dependency>
</dependencies>
</project>
1.2添加application.yml
elasticsearch:
host: 111.230.182.125
port: 9200
1.3添加@Configuation,使得项目在运行时候用到指定的elasticsearch服务器
package com.item.elasticsearch.config;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* 只当yml文件中的一个前缀
*/
@ConfigurationProperties(prefix = "elasticsearch")
@Slf4j
@Configuration
public class ElasticSearchConfig {
//region 配置相关参数。到时候程序一加载 就会去给对应参数加值
//elasticsearch.port \elasticsearch.host
private String host;
private Integer port;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
//endregion
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient highLevelClient = new RestHighLevelClient(
RestClient.builder(
new HttpHost(
host,
port,
"http"
)
));
log.info("RestHighLevelClient highLevelClient:{}", highLevelClient);
return highLevelClient;
}
}
1.4添加springboot启动类
package com.item.elasticsearch;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ElasticSearchApplication {
public static void main(String[] args) {
SpringApplication.run(ElasticSearchApplication.class, args);
}
}
1.5添加一个实体类。待会用到(domain下面)
package com.item.elasticsearch.domain;
import lombok.Data;
@Data
public class Person {
private String id;
private String name;
private Integer age;
private String address;
}
1.6添加一个测试Controller
package com.item.elasticsearch.Controller;
import com.alibaba.fastjson.JSON;
import com.item.elasticsearch.domain.Person;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("test")
public class TestController {
@Autowired
private RestHighLevelClient restHighLevelClient;
//region 1操作索引
@GetMapping("show")
public void show() {
log.info("test show restHighLevelClient,{}", restHighLevelClient);
}
/**
* 添加索引
*
* @throws IOException
*/
@GetMapping("addIndex")
public Boolean addIndex(String index) throws IOException {
//1使用client获取操作索引的对象
IndicesClient indicesClient = restHighLevelClient.indices();
//2具体操作 获取返回值
CreateIndexRequest createRequest = new CreateIndexRequest(index);
CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);
//3根据返回值 判断按结果
log.info("contextLoadsAuth response.isAcknowledged():{}", response.isAcknowledged());
return response.isAcknowledged();
}
/**
* 添加索引 以及映射
*
* @throws IOException
*/
@GetMapping("addIndexAndMapping")
public Boolean addIndexAndMapping(String index) throws IOException {
//1使用client获取操作索引的对象
IndicesClient indicesClient = restHighLevelClient.indices();
//2具体操作 获取返回值
CreateIndexRequest createRequest = new CreateIndexRequest(index);
//2.1映射信息
String mapping = "{ \"properties\": { \"name\": { \"type\": \"keyword\" }, \"age\": { \"type\": \"integer\" } } }";
createRequest.mapping(mapping, XContentType.JSON);
CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);
//3根据返回值 判断按结果
log.info("contextLoadsAuth response.isAcknowledged():{}", response.isAcknowledged());
return response.isAcknowledged();
}
/**
* 查询索引
*
* @param index
* @return
* @throws IOException
*/
@GetMapping("queryIndex")
public Object queryIndex(String index) throws IOException {
IndicesClient indices = restHighLevelClient.indices();
GetIndexRequest getRequest = new GetIndexRequest(index);
GetIndexResponse response = indices.get(getRequest, RequestOptions.DEFAULT);
//获取结果
Map<String, MappingMetadata> mappings = response.getMappings();
for (String key : mappings.keySet()) {
log.info("key:{};;getSourceAsMap:{}", key, mappings.get(key).getSourceAsMap());
}
return mappings;
}
/**
* 删除索引
*
* @param index
* @return
* @throws IOException
*/
@GetMapping("deleteIndex")
public Boolean deleteIndex(String index) throws IOException {
IndicesClient indices = restHighLevelClient.indices();
DeleteIndexRequest deleteRequest = new DeleteIndexRequest(index);
AcknowledgedResponse delete = indices.delete(deleteRequest, RequestOptions.DEFAULT);
return delete.isAcknowledged();
}
/**
* 判断索引是否存在
*
* @param index
* @return
* @throws IOException
*/
@GetMapping("existIndex")
public Boolean existIndex(String index) throws IOException {
IndicesClient indices = restHighLevelClient.indices();
GetIndexRequest getRequest = new GetIndexRequest(index);
boolean exists = indices.exists(getRequest, RequestOptions.DEFAULT);
return exists;
}
//endregion
//region 2文档操作
/**
* 添加文档
* (添加文档时,如果id存在则修改,id不存在则添加)
*
* @param index
* @param id
* @return
* @throws IOException
*/
@GetMapping("addDoc1")
public Object addDoc1(String index, String id) throws IOException {
Map data = new HashMap();
data.put("address", "北京");
data.put("name", "张三");
data.put("age", 20);
//1获取操作文档的对象
IndexRequest request = new IndexRequest(index).id(id).source(data);
//添加数据 获取打印结果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
return response;
}
/**
* 添加文档2
* 将对象转化为json
* (添加文档时,如果id存在则修改,id不存在则添加)
*
* @param index
* @param id
* @return
* @throws IOException
*/
@GetMapping("addDoc2")
public Object addDoc2(String index, String id) throws IOException {
Person person = new Person();
person.setAddress("北京");
person.setId(id);
person.setName("张三");
person.setAge(20);
String json = JSON.toJSONString(person);
//1获取操作文档的对象
IndexRequest request = new IndexRequest(index).id(id).source(json, XContentType.JSON);
//添加数据 获取打印结果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
return response;
}
/**
* 根据id查找文档
*
* @param index
* @param id
* @return
* @throws IOException
*/
@GetMapping("findDoc")
public Object findDoc(String index, String id) throws IOException {
GetRequest getRequest = new GetRequest(index, id);
GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
log.info("findDoc response:{}", response);
return response.getSourceAsMap();
}
/**
* 根据id删除文档
*
* @param index
* @param id
* @return
* @throws IOException
*/
@GetMapping("delDoc")
public Object delDoc(String index, String id) throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(index, id);
DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
return delete;
}
//endregion
}
1.7请求文档格式
https://docs.apipost.cn/preview/36b9603957752290/910c7793654e47b9