1.創建新springboot項目
//選中默認springboot版本 + NoSql 中的 es
//注意項目使用java8
//進入項目后,調整 項目使用 java1.8 + javascript EC6
//在pom 文件中 注意 設置使用的es版本、
<properties>
<java.version>1.8</java.version>
<!--自定義版本依賴-->
<elasticsearch.version>7.6.1 </elasticsearch.version>
</properties>
//准備 vue.js 和 axios.js
cnpm install vue
cnpm install axios
2.注意 springboot版本中es的版本 , 和本地版本 是否一致
//創建RestHighLevelClient 客戶端對象。 Config文件
// 1.找spring對象
// 2.放到spring中
@Configuration //xml
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client =new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
return client;
}
}
3.構建實體對象
package com.sinsoft.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/**
* @Auther Qianxy
* @Date 2020/7/26
*/
//AllArgsConstructor 有參
//NoArgsConstructor 無參
//Component 注入到 spring 中
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
public class User {
private String name;
private int age;
}
4.自定義es簡單API
package com.sinsoft;
import com.alibaba.fastjson.JSON;
import com.sinsoft.pojo.User;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
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.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
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.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
@SpringBootTest
class TonyEsApiApplicationTests {
//Qualifier 指定
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
@Test
void contextLoads() throws IOException {
//1.創建索引請求
CreateIndexRequest request = new CreateIndexRequest("kuang_index1");
//2.執行請求 indicesClient,請求后獲得響應
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
//獲取索引的類型
System.out.println(createIndexResponse.index());
//
System.out.println(createIndexResponse);
}
//獲取 索引
@Test
void testExistIndex () throws IOException{
//獲取 索引請求、
GetIndexRequest request = new GetIndexRequest("kuang_index");
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
//刪除索引
@Test
void testDeleIndex () throws IOException{
//刪除
DeleteIndexRequest request = new DeleteIndexRequest("kuang_index1");
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
//添加文檔
@Test
void testAddDocument()throws IOException{
//創建對象
User user = new User("狂神說", 3);
//創建請求
IndexRequest request = new IndexRequest("kuang_index");
//規則 put /kaung_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));
request.timeout("1s");
//將請求數據放在 json
request.source(JSON.toJSONString(user), XContentType.JSON);
//客戶端發送請求 , 獲取響應的結果
IndexResponse index = client.index(request, RequestOptions.DEFAULT);
System.out.println(index.toString());
System.out.println(index.status());
}
//獲取文檔
@Test
void testIsExist() throws IOException{
GetRequest getRequest = new GetRequest("kuang_index", "1");
//getRequest
//getRequest.fetchSourceContext(new FetchSourceContext(false));
//getRequest.storedFields("_none_");
boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
//獲得文檔信息
@Test
void testGetDocument() throws IOException{
GetRequest getRequest = new GetRequest("kuang_index","1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.toString());
System.out.println(getResponse);
}
//更新文檔
@Test
void testUpDateRequest() throws IOException{
UpdateRequest updateRequest = new UpdateRequest("kuang_index", "1");
updateRequest.timeout("1s");
User user = new User("qianaa1",21);
// kuang_index/_doc/1/_update
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(updateResponse.status());
}
//刪除文檔記錄
@Test
void testDeleteRequest() throws IOException{
DeleteRequest request = new DeleteRequest("kuang_index", "1");
request.timeout("1s");
DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
System.out.println(delete.status());
}
//批量插入數據
@Test
void testBulkRequest() throws IOException{
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userArrayList = new ArrayList<>();
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
userArrayList.add(new User("qianaa1",12));
//批處理請求
for (int i = 0; i <userArrayList.size() ; i++) {
bulkRequest.add(
new IndexRequest("kuang_index")
.id(""+(i+1))
.source(userArrayList.get(i),XContentType.JSON)
);
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
//是否失敗 false 就是沒有失敗
System.out.println(bulkResponse.hasFailures());
}
//查詢
// 1.SearchRequest 構建請求
// 2.SearchSourceBuilder 條件構造
// 3.TermQueryBuilder 精確條件構造 MatchAllQueryBuilder 全部查詢
// 4.SearchResponse client.search() 執行客戶端請求
// 5.searchResponse.getHits().getHits() 解析封裝的Json數據,需要getHits兩次
@Test
void testSeach() throws IOException{
SearchRequest searchRequest = new SearchRequest("kuang_index");
//構建搜索
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//高亮 API
//searchSourceBuilder.highlighter();
//精確搜索
TermQueryBuilder termQueryBuilder = new TermQueryBuilder("name","qianaa1");
//全部查詢,匹配索引
//MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
//執行精確查詢
searchSourceBuilder.query(termQueryBuilder);
//分頁 有默認值
//searchSourceBuilder.from();
//searchSourceBuilder.size();
//設定 過期時間
searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//將構建索引 放入請求
searchRequest.source(searchSourceBuilder);
//客戶端 進行查詢
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// es將客戶端查詢數據 分裝在Hits
// searchResponse.getHits() 獲取的java對象,json工具不能解析
//searchResponse.getHits().getHits() 獲取可以解析json對象
System.out.println(JSON.toJSONString(searchResponse.getHits().getHits()));
System.out.println("===================================================");
//展示對象
for (SearchHit documentFields:searchResponse.getHits().getHits() ) {
System.out.println(documentFields.getSourceAsMap());
}
}
}
