整合springboot
1.整合依賴
注意依賴版本和安裝的版本一致
<properties>
? ? <java.version>1.8</java.version>
? ? <!-- 統一版本 -->
? ? <elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
導入elasticsearch
<dependency>
? ? <groupId>org.springframework.boot</groupId>
? ? <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
提前導入fastjson、lombok
<dependency>
? ? <groupId>com.alibaba</groupId>
? ? <artifactId>fastjson</artifactId>
? ? <version>1.2.70</version>
</dependency>
<!-- lombok需要安裝插件 -->
<dependency>
? ? <groupId>org.projectlombok</groupId>
? ? <artifactId>lombok</artifactId>
? ? <optional>true</optional>
</dependency>
2.編寫配置類
@Configuration
public class ElasticSearchConfig {
? ? // 注冊 rest高級客戶端?
? ? @Bean
? ? public RestHighLevelClient restHighLevelClient(){
? ? ? ? RestHighLevelClient client = new RestHighLevelClient(
? ? ? ? ? ? ? ? RestClient.builder(
? ? ? ? ? ? ? ? ? ? ? ? new HttpHost("127.0.0.1",9200,"http")
? ? ? ? ? ? ? ? )
? ? ? ? );
? ? ? ? return client;
? ? }
}
3.創建實體
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
? ? private static final long serialVersionUID = -3843548915035470817L;
? ? private String name;
? ? private Integer age;
}
4.測試
1.注入RestHighLevelClient
@Autowired
public RestHighLevelClient restHighLevelClient;
4.2.測試創建索引
// 測試索引的創建, Request PUT liuyou_index
@Test
public void testCreateIndex() throws IOException {
? ? CreateIndexRequest request = new CreateIndexRequest("liuyou_index");
? ? CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
? ? System.out.println(response.isAcknowledged());// 查看是否創建成功
? ? System.out.println(response);// 查看返回對象
? ? restHighLevelClient.close();
}
3.獲得索引
// 測試獲取索引,并判斷其是否存在
@Test
public void testIndexIsExists() throws IOException {
? ? GetIndexRequest request = new GetIndexRequest("index");
? ? boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
? ? System.out.println(exists);// 索引是否存在
? ? restHighLevelClient.close();
}
4.刪除索引
// 測試索引刪除
@Test
public void testDeleteIndex() throws IOException {
? ? DeleteIndexRequest request = new DeleteIndexRequest("liuyou_index");
? ? AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
? ? System.out.println(response.isAcknowledged());// 是否刪除成功
? ? restHighLevelClient.close();
}
4.5測試創建文檔
// 測試添加文檔(先創建一個User實體類,添加fastjson依賴)
@Test
public void testAddDocument() throws IOException {
? ? // 創建一個User對象
? ? User liuyou = new User("liuyou", 18);
? ? // 創建請求
? ? IndexRequest request = new IndexRequest("liuyou_index");
? ? // 制定規則 PUT /liuyou_index/_doc/1
? ? request.id("1");// 設置文檔ID
? ? request.timeout(TimeValue.timeValueMillis(1000));// request.timeout("1s")
? ? // 將我們的數據放入請求中
? ? request.source(JSON.toJSONString(liuyou), XContentType.JSON);
? ? // 客戶端發送請求,獲取響應的結果
? ? IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
? ? System.out.println(response.status());// 獲取建立索引的狀態信息 CREATED
? ? System.out.println(response);// 查看返回內容 IndexResponse[index=liuyou_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
}
6.獲取文檔信息
// 測試獲得文檔信息
@Test
public void testGetDocument() throws IOException {
? ? GetRequest request = new GetRequest("liuyou_index","1");
? ? GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
? ? System.out.println(response.getSourceAsString());// 打印文檔內容
? ? System.out.println(request);// 返回的全部內容和命令是一樣的
? ? restHighLevelClient.close();
}
7.獲取文檔
// 獲取文檔,判斷是否存在 get /liuyou_index/_doc/1
@Test
public void testDocumentIsExists() throws IOException {
? ? GetRequest request = new GetRequest("liuyou_index", "1");
? ? // 不獲取返回的 _source的上下文了
? ? request.fetchSourceContext(new FetchSourceContext(false));
? ? request.storedFields("_none_");
? ? boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
? ? System.out.println(exists);
}
8.文檔更新
// 測試更新文檔內容
@Test
public void testUpdateDocument() throws IOException {
? ? UpdateRequest request = new UpdateRequest("liuyou_index", "1");
? ? User user = new User("lmk",11);
? ? request.doc(JSON.toJSONString(user),XContentType.JSON);
? ? UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
? ? System.out.println(response.status()); // OK
? ? restHighLevelClient.close();
}
9.文檔刪除
// 測試刪除文檔
@Test
public void testDeleteDocument() throws IOException {
? ? DeleteRequest request = new DeleteRequest("liuyou_index", "1");
? ? request.timeout("1s");
? ? DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
? ? System.out.println(response.status());// OK
}
10.文檔查詢
// 查詢
// SearchRequest 搜索請求
// SearchSourceBuilder 條件構造
// HighlightBuilder 高亮
// TermQueryBuilder 精確查詢
// MatchAllQueryBuilder
// xxxQueryBuilder ...
@Test
public void testSearch() throws IOException {
? ? // 1.創建查詢請求對象
? ? SearchRequest searchRequest = new SearchRequest();
? ? // 2.構建搜索條件
? ? SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
? ? // (1)查詢條件 使用QueryBuilders工具類創建
? ? // 精確查詢
? ? TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "liuyou");
? ? // ? ? ? ?// 匹配查詢
? ? // ? ? ? ?MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
? ? // (2)其他<可有可無>:(可以參考 SearchSourceBuilder 的字段部分)
? ? // 設置高亮
? ? searchSourceBuilder.highlighter(new HighlightBuilder());
? ? // ? ? ? ?// 分頁
? ? // ? ? ? ?searchSourceBuilder.from();
? ? // ? ? ? ?searchSourceBuilder.size();
? ? searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
? ? // (3)條件投入
? ? searchSourceBuilder.query(termQueryBuilder);
? ? // 3.添加條件到請求
? ? searchRequest.source(searchSourceBuilder);
? ? // 4.客戶端查詢請求
? ? SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
? ? // 5.查看返回結果
? ? SearchHits hits = search.getHits();
? ? System.out.println(JSON.toJSONString(hits));
? ? System.out.println("=======================");
? ? for (SearchHit documentFields : hits.getHits()) {
? ? ? ? System.out.println(documentFields.getSourceAsMap());
? ? }
}
11.批量添加文檔
// 特殊的,真的項目一般會 批量插入數據
@Test
public void testBulk() throws IOException {
? ? BulkRequest bulkRequest = new BulkRequest();
? ? bulkRequest.timeout("10s");
? ? ArrayList<User> users = new ArrayList<>();
? ? users.add(new User("liuyou-1",1));
? ? users.add(new User("liuyou-2",2));
? ? users.add(new User("liuyou-3",3));
? ? users.add(new User("liuyou-4",4));
? ? users.add(new User("liuyou-5",5));
? ? users.add(new User("liuyou-6",6));
? ? // 批量請求處理
? ? for (int i = 0; i < users.size(); i++) {
? ? ? ? bulkRequest.add(
? ? ? ? ? ? ? ? // 這里是數據信息
? ? ? ? ? ? ? ? new IndexRequest("bulk")
? ? ? ? ? ? ? ? ? ? ? ? .id(""+(i + 1)) // 沒有設置id 會自定生成一個隨機id
? ? ? ? ? ? ? ? ? ? ? ? .source(JSON.toJSONString(users.get(i)),XContentType.JSON)
? ? ? ? );
? ? }
? ? BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
? ? System.out.println(bulk.status());// ok
}