1 搭建SpringBoot工程
2 引入ElasticSearch相關(guān)坐標(biāo)。
<properties>
<!--一定重新定義版本 版本號(hào)一定要和您所安裝的ES版本號(hào)一致-->
<elasticsearch.version>7.4.0</elasticsearch.version>
</properties>
<dependencies>
<!--引入es的坐標(biāo)-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>
................
3 編寫核心配置類
編寫核心配置文件:
這里可以不寫在配置,可以直接寫在代碼中,只是一般都是寫在配置文件中
#這個(gè)是我們自寫的,如果看有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;
}
}
4 測(cè)試客戶端對(duì)象
記得把maven的單元測(cè)試關(guān)了
注意:使用@Autowired注入RestHighLevelClient 如果報(bào)紅線,則是因?yàn)榕渲妙愃诘陌蜏y(cè)試類所在的包,包名不一致造成的
@SpringBootTest
class SpringElasticsearchApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
void contextLoads() {
System.out.println(restHighLevelClient);
}
}
(二)操作ElasticSearch
操作索引要索引的對(duì)象來(lái)進(jìn)行操作
//獲取索引對(duì)象 這個(gè)對(duì)象提供操作索引的方法
IndicesClient indices = client.indices();
//添加索引對(duì)象 RequestOptions.DEFAULT默認(rèn)的動(dòng)作
indices.create(new CreateIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//查詢索引對(duì)象
indices.get(new GetIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//刪除索引對(duì)象
indices.delete(new DeleteIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
1 添加索引
/**
* 添加索引:
* @throws Exception
*/
@Test
public void addindex() throws IOException {
// 獲取索引對(duì)象
IndicesClient indices = client.indices();
//create() CreateIndexRequest("索引名稱") RequestOptions.DEFAULT默的行為
CreateIndexResponse indexResponse = indices.create(new CreateIndexRequest("student123"), RequestOptions.DEFAULT);
System.out.println(indexResponse.isAcknowledged());
}
2 添加索引,并添加映射
/**
* 創(chuàng)建索引并且添加映射
* @throws IOException
*/
@Test
public void addIndexAndMapping() throws IOException {
//1.使用client獲取操作索引的對(duì)象
IndicesClient indicesClient = restHighLevelClient.indices();
//2.具體操作,獲取返回值
CreateIndexRequest createRequest = new CreateIndexRequest("offcn");
//2.1 設(shè)置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執(zhí)行創(chuàng)建,返回對(duì)象
CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);
//3.根據(jù)返回值判斷結(jié)果
System.out.println(response.isAcknowledged());
}
3 查詢、刪除、判斷索引
3.1 查詢索引
/**
* 查詢索引
*/
@Test
public void queryIndex() throws IOException {
//1:使用client獲取操作索引的對(duì)象
IndicesClient indices = restHighLevelClient.indices();
//2:獲得對(duì)象,執(zhí)行具體的操作
//2.1 創(chuàng)建獲取索引的請(qǐng)求對(duì)象,設(shè)置索引名稱
GetIndexRequest getReqeust = new GetIndexRequest("offcn");
//2.2 執(zhí)行查詢,獲得返回值
GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);
//3:獲取結(jié)果,遍歷
Map<String, MappingMetaData> mappings = response.getMappings();
for (String key : mappings.keySet()) {
System.out.println(key + ":" + mappings.get(key).getSourceAsMap());
}
}
3.2 刪除索引
/**
* 刪除索引
*/
@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());
}
3.3 索引是否存在
/**
* 判斷索引是否存在
*/
@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("索引不存在");
}
}
4 操作文檔
4.1 添加文檔
添加文檔,使用map作為數(shù)據(jù)
/**
* 添加文檔,使用map作為數(shù)據(jù)
*/
@Test
public void addDoc() throws IOException {
//數(shù)據(jù)對(duì)象,map key要與映射屬性對(duì)應(yīng)
Map data = new HashMap();
data.put("address", "北京昌平");
data.put("name", "馬同志");
data.put("age", 20);
//1:獲取操作文檔的對(duì)象
IndexRequest request = new IndexRequest("offcn").id("1").source(data);
//2:添加數(shù)據(jù),獲取結(jié)果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//3:打印響應(yīng)結(jié)果
System.out.println(response.getResult());
}
添加文檔,使用對(duì)象作為數(shù)據(jù)
添加依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
創(chuàng)建實(shí)體類,屬性名與映射字段名對(duì)應(yīng)
@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"
}
}
}
}
}
/**
* 添加文檔,使用對(duì)象作為數(shù)據(jù)
*/
@Test
public void addDoc2() throws IOException {
//數(shù)據(jù)對(duì)象,javaObject
Student student=new Student("kaka",22,"南沙中公教育");
//將對(duì)象轉(zhuǎn)為json
String data = JSON.toJSONString(p);
//1:獲取操作文檔的對(duì)象
IndexRequest request = new IndexRequest("offcn").id(p.getId()).source(data, XContentType.JSON);
//2:添加數(shù)據(jù),獲取結(jié)果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//3:打印響應(yīng)結(jié)果
System.out.println(response.getId());
}
4.2 修改文檔:添加文檔時(shí),如果id存在則修改,id不存在則添加
/**
* 修改文檔:添加文檔時(shí),如果id存在則修改,id不存在則添加
*/
@Test
public void updateDoc() throws IOException {
//數(shù)據(jù)對(duì)象,map
Map data = new HashMap();
data.put("address", "北京昌平");
data.put("name", "朱同志");
data.put("age", 20);
//1:獲取操作文檔的對(duì)象
IndexRequest request = new IndexRequest("offcn").id("1").source(data);
//2:添加數(shù)據(jù),獲取結(jié)果
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
//3:打印響應(yīng)結(jié)果
System.out.println(response.getId());
}
4.3 根據(jù)id查詢文檔
@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轉(zhuǎn)換為 stuent
//JSON字符串-->JSON對(duì)象
JSONObject jsonObject = JSONObject.parseObject(sourceAsString);
//JSON對(duì)象-->Java對(duì)象
Student student = JSONObject.toJavaObject(jsonObject, Student.class);
System.out.println(student);
}
4.4 根據(jù)id刪除文檔
/**
* 根據(jù)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());
}
總結(jié):
//添加、修改 第一個(gè):索引名稱 第二個(gè)是文檔id 第三個(gè)是文檔內(nèi)容
restHighLevelClient
.index( new IndexRequest("offcn_index2").id("as1122").source(data),RequestOptions.DEFAULT)
//查詢 第一個(gè)參數(shù)是索引名稱 第二個(gè)是文檔id
restHighLevelClient.get( new GetRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)
//刪除 第一個(gè)參數(shù)是索引名稱 第二個(gè)是文檔id
restHighLevelClient.delete( new DeleteRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)
(三)ElasticSearch的文檔批量操作
1 bulk文檔 批量操作腳本實(shí)現(xiàn)
需求:同時(shí)完成【刪除,更新,添加】操作 這里的JSON格式不能格式化
POST _bulk
{"delete":{"_index":"person1","_id":"4"}}
{"create":{"_index":"person1","_id":"5"}}
{"name":"八號(hào)","age":18,"address":"北京"}
{"update":{"_index":"person1","_id":"2"}}
{"doc":{"name":"2號(hào)"}}
查詢運(yùn)行結(jié)果~
2 bulk批量操作JavaAPI 實(shí)現(xiàn)
/**
* Bulk 批量操作
*/
@Test
public void test2() throws IOException {
//創(chuàng)建bulkrequest對(duì)象,整合所有操作
BulkRequest bulkRequest =new BulkRequest();
/*
# 1. 刪除5號(hào)記錄
# 2. 添加6號(hào)記錄
# 3. 修改3號(hào)記錄 名稱為 “三號(hào)”
*/
//添加對(duì)應(yīng)操作
//1. 刪除5號(hào)記錄
DeleteRequest deleteRequest=new DeleteRequest("person1","5");
bulkRequest.add(deleteRequest);
//2. 添加6號(hào)記錄
Map<String, Object> map=new HashMap<>();
map.put("name","六號(hào)");
IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
bulkRequest.add(indexRequest);
//3. 修改3號(hào)記錄 名稱為 “三號(hào)”
Map<String, Object> mapUpdate=new HashMap<>();
mapUpdate.put("name","三號(hào)");
UpdateRequest updateRequest=new UpdateRequest("person1","3").doc(mapUpdate);
bulkRequest.add(updateRequest);
//執(zhí)行批量操作
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response.status());
}
官方文檔:
https://www.elastic.co/guide/en/elasticsearch/client/index.html文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-745528.html
Java REST Client 》Java High Level REST Client文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-745528.html
到了這里,關(guān)于SpringBoot整合ElasticSearch之Java High Level REST Client的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!