<properties>
<elasticsearch.version>7.4.0elasticsearch.version>
properties>
<dependencies>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-high-level-clientartifactId>
<version>7.4.0version>
dependency>
................
编写核心配置文件:
这里可以不写在配置,可以直接写在代码中,只是一般都是写在配置文件中
#这个是我们自写的,如果看有es提示,不要用
elasticsearch:
host: 192.168.126.20
port: 9200
编写核心配置类
@Configuration
@ConfigurationProperties(prefix="elasticsearch")
public class ElasticSearchConfig {
private String host;
private int port;
@Bean
public RestHighLevelClient client(){
return new RestHighLevelClient(RestClient.builder(
new HttpHost(host,port,"http")
));
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
记得把maven的单元测试关了
注意:使用@Autowired注入RestHighLevelClient 如果报红线,则是因为配置类所在的包和测试类所在的包,包名不一致造成的
@SpringBootTest
class SpringElasticsearchApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
void contextLoads() {
System.out.println(restHighLevelClient);
}
}
操作索引要索引的对象来进行操作
//获取索引对象 这个对象提供操作索引的方法
IndicesClient indices = client.indices();
//添加索引对象 RequestOptions.DEFAULT默认的动作
indices.create(new CreateIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//查询索引对象
indices.get(new GetIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//删除索引对象
indices.delete(new DeleteIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
/**
* 添加索引:
* @throws Exception
*/
@Test
public void addindex() throws IOException {
// 获取索引对象
IndicesClient indices = client.indices();
//create() CreateIndexRequest("索引名称") RequestOptions.DEFAULT默的行为
CreateIndexResponse indexResponse = indices.create(new CreateIndexRequest("student123"), RequestOptions.DEFAULT);
System.out.println(indexResponse.isAcknowledged());
}
/**
* 创建索引并且添加映射
* @throws IOException
*/
@Test
public void addIndexAndMapping() throws IOException {
//1.使用client获取操作索引的对象
IndicesClient indicesClient = restHighLevelClient.indices();
//2.具体操作,获取返回值
CreateIndexRequest createRequest = new CreateIndexRequest("offcn");
//2.1 设置mappings
String mapping = "{\n" +
" \"properties\" : {\n" +
" \"address\" : {\n" +
" \"type\" : \"text\",\n" +
" \"analyzer\" : \"ik_max_word\"\n" +
" },\n" +
" \"age\" : {\n" +
" \"type\" : \"long\"\n" +
" },\n" +
" \"name\" : {\n" +
" \"type\" : \"keyword\"\n" +
" }\n" +
" }\n" +
" }";
createRequest.mapping(mapping, XContentType.JSON);
//2.2执行创建,返回对象
CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);
//3.根据返回值判断结果
System.out.println(response.isAcknowledged());
}
/**
* 查询索引
*/
@Test
public void queryIndex() throws IOException {
//1:使用client获取操作索引的对象
IndicesClient indices = restHighLevelClient.indices();
//2:获得对象,执行具体的操作
//2.1 创建获取索引的请求对象,设置索引名称
GetIndexRequest getReqeust = new GetIndexRequest("offcn");
//2.2 执行查询,获得返回值
GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);
//3:获取结果,遍历
Map<String, MappingMetaData> mappings = response.getMappings();
for (String key : mappings.keySet()) {
System.out.println(key + ":" + mappings.get(key).getSourceAsMap());
}
}
/**
* 删除索引
*/
@Test
public void deleteIndex() throws IOException {
IndicesClient indices = restHighLevelClient.indices();
DeleteIndexRequest deleteRequest = new DeleteIndexRequest("offcn");
AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}
/**
* 判断索引是否存在
*/
@Test
public void getIndex() throws IOException {
IndicesClient indices = client.indices();
GetIndexRequest student0517 = new GetIndexRequest("student0517");
boolean exists = indices.exists(student0517, RequestOptions.DEFAULT);
if(exists){
GetIndexResponse indexResponse = indices.get(student0517, RequestOptions.DEFAULT);
Map<String, MappingMetaData> mappings = indexResponse.getMappings();
System.out.println(mappings);
}else{
System.out.println("索引不存在");
}
}
添加文档,使用map作为数据
/**
* 添加文档,使用map作为数据
*/
@Test
public void addDoc() throws IOException {
//数据对象,map key要与映射属性对应
Map data = new HashMap();
data.put("address", "北京昌平");
data.put("name", "马同志");
data.put("age", 20);
//1:获取操作文档的对象
IndexRequest request = new IndexRequest("offcn").id("1").source(data);
//2:添加数据,获取结果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//3:打印响应结果
System.out.println(response.getResult());
}
添加文档,使用对象作为数据
添加依赖
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.76version>
dependency>
创建实体类,属性名与映射字段名对应
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private String brand;
private Integer price;
private String title;
}
{
"sutdent78" : {
"mappings" : {
"properties" : {
"brand" : {
"type" : "keyword"
},
"price" : {
"type" : "integer"
},
"title" : {
"type" : "text",
"analyzer" : "ik_max_word"
}
}
}
}
}
/**
* 添加文档,使用对象作为数据
*/
@Test
public void addDoc2() throws IOException {
//数据对象,javaObject
Student student=new Student("kaka",22,"南沙中公教育");
//将对象转为json
String data = JSON.toJSONString(p);
//1:获取操作文档的对象
IndexRequest request = new IndexRequest("offcn").id(p.getId()).source(data, XContentType.JSON);
//2:添加数据,获取结果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//3:打印响应结果
System.out.println(response.getId());
}
/**
* 修改文档:添加文档时,如果id存在则修改,id不存在则添加
*/
@Test
public void updateDoc() throws IOException {
//数据对象,map
Map data = new HashMap();
data.put("address", "北京昌平");
data.put("name", "朱同志");
data.put("age", 20);
//1:获取操作文档的对象
IndexRequest request = new IndexRequest("offcn").id("1").source(data);
//2:添加数据,获取结果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//3:打印响应结果
System.out.println(response.getId());
}
@Test
public void getDoc() throws IOException {
GetRequest getRequest = new GetRequest("sutdent78").id("1002");
GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
//集合方式
Map<String, Object> source = documentFields.getSource();
for (String key : source.keySet()) {
System.out.println(source.get(key));
}
//字符串 -----JSON
String sourceAsString = documentFields.getSourceAsString();
System.out.println(sourceAsString);
//把JSON转换为 stuent
//JSON字符串-->JSON对象
JSONObject jsonObject = JSONObject.parseObject(sourceAsString);
//JSON对象-->Java对象
Student student = JSONObject.toJavaObject(jsonObject, Student.class);
System.out.println(student);
}
/**
* 根据id删除文档
*/
@Test
public void delDoc() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("offcn", "1");
DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(response.getId());
}
总结:
//添加、修改 第一个:索引名称 第二个是文档id 第三个是文档内容
restHighLevelClient
.index( new IndexRequest("offcn_index2").id("as1122").source(data),RequestOptions.DEFAULT)
//查询 第一个参数是索引名称 第二个是文档id
restHighLevelClient.get( new GetRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)
//删除 第一个参数是索引名称 第二个是文档id
restHighLevelClient.delete( new DeleteRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)
需求:同时完成【删除,更新,添加】操作 这里的JSON格式不能格式化
POST _bulk
{"delete":{"_index":"person1","_id":"4"}}
{"create":{"_index":"person1","_id":"5"}}
{"name":"八号","age":18,"address":"北京"}
{"update":{"_index":"person1","_id":"2"}}
{"doc":{"name":"2号"}}
查询运行结果~
/**
* Bulk 批量操作
*/
@Test
public void test2() throws IOException {
//创建bulkrequest对象,整合所有操作
BulkRequest bulkRequest =new BulkRequest();
/*
# 1. 删除5号记录
# 2. 添加6号记录
# 3. 修改3号记录 名称为 “三号”
*/
//添加对应操作
//1. 删除5号记录
DeleteRequest deleteRequest=new DeleteRequest("person1","5");
bulkRequest.add(deleteRequest);
//2. 添加6号记录
Map<String, Object> map=new HashMap<>();
map.put("name","六号");
IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
bulkRequest.add(indexRequest);
//3. 修改3号记录 名称为 “三号”
Map<String, Object> mapUpdate=new HashMap<>();
mapUpdate.put("name","三号");
UpdateRequest updateRequest=new UpdateRequest("person1","3").doc(mapUpdate);
bulkRequest.add(updateRequest);
//执行批量操作
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response.status());
}
官方文档:
https://www.elastic.co/guide/en/elasticsearch/client/index.html
Java REST Client 》Java High Level REST Client