上一章:《第三章:ElasticSearch相關概念》
文章目錄
-
- 4.1 導入elasticsearch依賴
- 4.2 建立進階用戶端
- 4.3 基本用法
-
- 1.建立、判斷存在、删除索引
- 2.對文檔的CRUD
- 3.批量新增文檔資料
- 4.查詢所有、模糊查詢、分頁查詢、排序、高亮顯示
- 4.4 總結
-
- 1.大緻流程
- 2.注意事項
上述部分為理論部分,本章跟着我一起來看一下具體開發中es是如何使用的
本章的完整代碼在文末可以自行檢視下載下傳4.1 導入elasticsearch依賴
在pom.xml裡加入如下依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
我的SpringBoot版本:
2.6.2引入之後記得要看一下你的依賴版本是否和es的版本是否适配,如果不一緻,會連接配接失敗
啟動es,在浏覽器輸入http://localhost:9200/檢視es版本
很明顯,我們的版本是不相容的,我找了半天spring-boot-starter-data-elasticsearch依賴包也沒找到适配es 8.6.1的依賴,為了不影響進度,我先退而求其次,先使用7.15.2這個版本的es
安裝包:https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.15.2-windows-x86_64.zip
安裝過程和我們第二章的過程一樣,詳情可參考:《第二章:ElasticSearch安裝》
安裝之後,我們可以看到我們的版本号已經變為7.15.2啦
4.2 建立進階用戶端
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
return client;
}
}
如果你的es是部署在伺服器上,那麼127.0.0.1則需要改成你伺服器的ip位址
4.3 基本用法
1.建立、判斷存在、删除索引
- 建立索引
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 建立索引
*
* @return
* @throws IOException
*/
@GetMapping("/index/createIndex")
public Object createIndex() throws IOException {
//1.建立索引請求
CreateIndexRequest request = new CreateIndexRequest("ninesunindex");
//2.用戶端執行請求IndicesClient,執行create方法建立索引,請求後獲得響應
CreateIndexResponse response =
restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
return response;
}
可以看到索引已經建立成功
PS:如果不知道索引以及我們後面提到的名次概念,可以花幾分鐘讀一下:《第三章:ElasticSearch相關概念》- 查詢索引
/**
* 查詢索引
*
* @return
* @throws IOException
*/
@GetMapping("/index/searchIndex")
public Object searchIndex() throws IOException {
//1.查詢索引請求
GetIndexRequest request = new GetIndexRequest("ninesunindex");
//2.執行exists方法判斷是否存在
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
return exists;
}
- 删除索引
/**
* 删除索引
*
* @return
* @throws IOException
*/
@GetMapping("/index/delIndex")
public Object delIndex() throws IOException {
//1.删除索引請求
DeleteIndexRequest request = new DeleteIndexRequest("ninesunindex");
//執行delete方法删除指定索引
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
return delete.isAcknowledged();
}
2.對文檔的CRUD
建立文檔:
注意:如果添加時不指定文檔ID,他就會随機生成一個ID,ID唯一。建立文檔時若該ID已存在,發送建立文檔請求後會更新文檔中的資料
。
- 新增文檔
/**
* 新增文檔
*
* @return
* @throws IOException
*/
@GetMapping("/document/add")
public Object add() throws IOException {
//1.建立對象
User user = new User("Go", 21, new String[]{"内卷", "吃飯"});
//2.建立請求
IndexRequest request = new IndexRequest("ninesunindex");
//3.設定規則 PUT /ljx666/_doc/1
//設定文檔id=6,設定逾時=1s等,不設定會使用預設的
//同時支援鍊式程式設計如 request.id("6").timeout("1s");
request.id("6");
request.timeout("1s");
//4.将資料放入請求,要将對象轉化為json格式
//XContentType.JSON,告訴它傳的資料是JSON類型
request.source(JSONValue.toJSONString(user), XContentType.JSON);
//5.用戶端發送請求,擷取響應結果
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
System.out.println(indexResponse.status());
return indexResponse;
}
- 擷取文檔中的資料
/**
* 擷取文檔中的資料
*
* @return
* @throws IOException
*/
@GetMapping("/document/get")
public Object get() throws IOException {
//1.建立請求,指定索引、文檔id
GetRequest request = new GetRequest("ninesunindex", "6");
GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
System.out.println(getResponse);//擷取響應結果
//getResponse.getSource() 傳回的是Map集合
System.out.println(getResponse.getSourceAsString());//擷取響應結果source中内容,轉化為字元串
return getResponse;
}
- 更新文檔資料
注意:需要将User對象中的屬性全部指定值,不然會被設定為空,如User隻設定了名稱,那麼隻有名稱會被修改成功,其他會被修改為null。
/**
* 更新文檔資料
*
* @return
* @throws IOException
*/
@GetMapping("/document/update")
public Object update() throws IOException {
//1.建立請求,指定索引、文檔id
UpdateRequest request = new UpdateRequest("ninesunindex", "6");
User user = new User("GoGo", 21, new String[]{"内卷", "吃飯"});
//将建立的對象放入文檔中
request.doc(JSONValue.toJSONString(user), XContentType.JSON);
UpdateResponse updateResponse = restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());//更新成功傳回OK
return updateResponse;
}
- 删除文檔資料
/**
* 删除文檔資料
*
* @return
* @throws IOException
*/
@GetMapping("/document/delete")
public Object delete() throws IOException {
//1.建立删除文檔請求
DeleteRequest request = new DeleteRequest("ninesunindex", "6");
DeleteResponse deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());//更新成功傳回OK
return deleteResponse;
}
3.批量新增文檔資料
- 批量新增文檔資料
/**
* 批量新增文檔資料
*
* @return
* @throws IOException
*/
@GetMapping("/document/addBatch")
public Object addBatch() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
//設定逾時
bulkRequest.timeout("10s");
List<User> list = new ArrayList<>();
list.add(new User("Java", 25, new String[]{"内卷"}));
list.add(new User("Go", 18, new String[]{"内卷"}));
list.add(new User("C", 30, new String[]{"内卷"}));
list.add(new User("C++", 26, new String[]{"内卷"}));
list.add(new User("Python", 20, new String[]{"内卷"}));
int id = 1;
//批量處理請求
for (User u : list) {
//不設定id會生成随機id
bulkRequest.add(new IndexRequest("ninesunindex")
.id("" + (id++))
.source(JSONValue.toJSONString(u), XContentType.JSON));
}
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());//是否執行失敗,false為執行成功
return bulkResponse;
}
4.查詢所有、模糊查詢、分頁查詢、排序、高亮顯示
@GetMapping("test")
public Object test() throws IOException {
SearchRequest searchRequest = new SearchRequest("ninesunindex");//裡面可以放多個索引
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//構造搜尋條件
//此處可以使用QueryBuilders工具類中的方法
//1.查詢所有
sourceBuilder.query(QueryBuilders.matchAllQuery());
//2.查詢name中含有Java的
sourceBuilder.query(QueryBuilders.multiMatchQuery("java", "userName"));
//3.分頁查詢
sourceBuilder.from(0).size(5);
//4.按照score正序排列
sourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.ASC));
//5.按照id倒序排列(score會失效傳回NaN)
sourceBuilder.sort(SortBuilders.fieldSort("_id").order(SortOrder.DESC));
//6.給指定字段加上指定高亮樣式
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("userName").preTags("<span style='color:red;'>").postTags("</span>");
sourceBuilder.highlighter(highlightBuilder);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//擷取總條數
System.out.println(searchResponse.getHits().getTotalHits().value);
//輸出結果資料(如果不設定傳回條數,大于10條預設隻傳回10條)
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
System.out.println("分數:" + hit.getScore());
Map<String, Object> source = hit.getSourceAsMap();
System.out.println("index->" + hit.getIndex());
System.out.println("id->" + hit.getId());
for (Map.Entry<String, Object> s : source.entrySet()) {
System.out.println(s.getKey() + "--" + s.getValue());
}
}
return searchResponse;
}
4.4 總結
1.大緻流程
建立對應的請求 --> 設定請求(添加規則,添加資料等) --> 執行對應的方法(傳入請求,預設請求選項)–> 接收響應結果(執行方法傳回值)–> 輸出響應結果中需要的資料(source,status等)
2.注意事項
如果不指定id,會自動生成一個随機id
正常情況下,不應該這樣使用new IndexRequest(“indexName”),如果索引發生改變了,那麼代碼都需要修改,
可以定義一個枚舉類或者一個專門存放常量的類,将變量用final static等進行修飾,并指定索引值。其他地方引用該常量即可,需要修改也隻需修改該類即可。
elasticsearch相關的東西,版本都必須一緻,不然會報錯
elasticsearch很消耗記憶體,建議在記憶體較大的伺服器上運作elasticsearch,否則會因為記憶體不足導緻elasticsearch自動killed
git位址:https://gitee.com/ninesuntec/es-better.git
下一章:《第五章:ElasticSearchRepository和ElasticsearchRestTemplate的使用
》