RestClient 访问elasticsearch
生活随笔
收集整理的這篇文章主要介紹了
RestClient 访问elasticsearch
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1。引入依賴
1)引入es的RestHighLevelClient依賴:
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency>2)因為SpringBoot默認的ES版本是7.6.2,所以我們需要覆蓋默認的ES版本:
<properties><java.version>1.8</java.version><elasticsearch.version>7.12.1</elasticsearch.version> </properties>3)初始化RestHighLevelClient:
初始化的代碼如下:
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.150.101:9200") ));2.創建索引庫和刪除索引庫
存儲的是新增索引庫的語句
package cn.itcast.hotel;public class HotelConstants {public static final String MAPPING_TEMPLATE = "{\n" +" \"mappings\": {\n" +" \"properties\": {\n" +" \"id\": {\n" +" \"type\": \"keyword\"\n" +" },\n" +" \"name\":{\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\",\n" +" \"copy_to\": \"all\"\n" +" },\n" +" \"address\":{\n" +" \"type\": \"keyword\",\n" +" \"index\": false\n" +" },\n" +" \"price\":{\n" +" \"type\": \"integer\"\n" +" },\n" +" \"score\":{\n" +" \"type\": \"integer\"\n" +" },\n" +" \"brand\":{\n" +" \"type\": \"keyword\",\n" +" \"copy_to\": \"all\"\n" +" },\n" +" \"city\":{\n" +" \"type\": \"keyword\",\n" +" \"copy_to\": \"all\"\n" +" },\n" +" \"starName\":{\n" +" \"type\": \"keyword\"\n" +" },\n" +" \"business\":{\n" +" \"type\": \"keyword\"\n" +" },\n" +" \"location\":{\n" +" \"type\": \"geo_point\"\n" +" },\n" +" \"pic\":{\n" +" \"type\": \"keyword\",\n" +" \"index\": false\n" +" },\n" +" \"all\":{\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\"\n" +" }\n" +" }\n" +" }\n" +"}"; }新增和刪除索引庫操作?
import org.apache.http.HttpHost; import org.apache.http.client.methods.HttpPost; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.common.xcontent.XContentType; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest;import java.io.IOException;@SpringBootTest class HotelSuoYinTest {private RestHighLevelClient client;@BeforeEachvoid setup() {this.client =new RestHighLevelClient(RestClient.builder(HttpHost.create("http://101.43.94.150:9200")));}@AfterEachvoid shutdown() throws IOException {this.client.close();} // indices() 有這個,就是索引庫的操作@Testvoid test() throws IOException { // 創建request對象CreateIndexRequest request = new CreateIndexRequest("hotel"); // 準備請求的參數 dsl語句request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON); // 發送請求client.indices().create(request, RequestOptions.DEFAULT);}@Testvoid deltest() throws IOException { // 創建request對象DeleteIndexRequest request = new DeleteIndexRequest("hotel"); // 發送請求client.indices().delete(request, RequestOptions.DEFAULT);} }判斷索引庫是不是存在?
@Test void testExistsHotelIndex() throws IOException {// 1.創建Request對象GetIndexRequest request = new GetIndexRequest("hotel");// 2.發送請求boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);// 3.輸出System.err.println(exists ? "索引庫已經存在!" : "索引庫不存在!"); }索引庫操作的基本步驟:
-
初始化RestHighLevelClient
-
創建XxxIndexRequest。XXX是Create、Get、Delete
-
準備DSL( Create時需要,其它是無參)
-
發送請求。調用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete
3.刪除文檔 修改文檔 新增文檔 批量添加文檔
因為mysql查詢出來的hotel信息經緯度信息是分開的,但是eleasticsearch的地理坐標要求是一個String類型,中間用逗號分開,所以要轉為hotelDoc
//文檔,相當于mysql中的行 //#查詢一條文檔(記錄)的 dsl語句 // GET /heima/_doc/1 @SpringBootTest public class DocumentTest {private RestHighLevelClient client;@AutowiredHotelService hotelService;// 插入新數據@Testpublic void testadd() throws IOException {Hotel hotel = hotelService.getById(61083L);HotelDoc hotelDoc = new HotelDoc(hotel); // 創建request,并指明要處理的索引是hotel,記錄號是 hotelDoc.getId()IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);client.index(request, RequestOptions.DEFAULT);}// 查詢某條數據@Testpublic void testquery() throws IOException {GetRequest request = new GetRequest("hotel", "61083");GetResponse response = client.get(request, RequestOptions.DEFAULT);String json = response.getSourceAsString();HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);System.out.println(hotelDoc);}//更新某條數據@Testpublic void testupdate() throws IOException {Hotel hotel = hotelService.getById(61083L);HotelDoc hotelDoc = new HotelDoc(hotel);UpdateRequest request = new UpdateRequest("hotel", "61083");request.doc("price", "952");request.doc("address", "北京飯店");client.update(request, RequestOptions.DEFAULT);}// 刪除某條數據@Testvoid testDeleteDocument() throws IOException {// 1.準備RequestDeleteRequest request = new DeleteRequest("hotel", "61083");// 2.發送請求client.delete(request, RequestOptions.DEFAULT);}@Testvoid testpiliangadd() throws IOException {List<Hotel> hotels = hotelService.list();BulkRequest request = new BulkRequest();for (Hotel hotel : hotels) {HotelDoc hotelDoc = new HotelDoc(hotel);request.add(new IndexRequest("hotel").id(hotelDoc.getId() + "").source(JSON.toJSONString(hotelDoc), XContentType.JSON));}client.bulk(request, RequestOptions.DEFAULT);}@BeforeEachvoid setup() {this.client =new RestHighLevelClient(RestClient.builder(HttpHost.create("http://101.43.94.150:9200")));}@AfterEachvoid shutdown() throws IOException {this.client.close();} }4.查詢文檔
package cn.itcast.hotel;import cn.itcast.hotel.pojo.HotelDoc; import com.alibaba.fastjson.JSON; import org.apache.http.HttpHost; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.SortOrder; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest;import java.io.IOException; import java.util.Map;@SpringBootTest public class QueryTest {private RestHighLevelClient client;//查詢全部文檔@Testvoid testmatchall() throws IOException { // 1. 準備requestSearchRequest request = new SearchRequest("hotel"); // 2. 準備dslrequest.source().query(QueryBuilders.matchAllQuery()); // 3.發送請求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}//全文檢索查詢@Testvoid testquerycheck() throws IOException { // 1. 準備requestSearchRequest request = new SearchRequest("hotel");// 2. 準備dslrequest.source().query(QueryBuilders.matchQuery("all", "如家")); // 3.發送請求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleResponse(response);}//boolean復合查詢@Testvoid testBool() throws IOException {// 1.準備RequestSearchRequest request = new SearchRequest("hotel");// 2.準備DSL// 2.1.準備BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();// 2.2.添加termboolQuery.must(QueryBuilders.termQuery("city", "上海"));// 2.3.添加rangeboolQuery.filter(QueryBuilders.rangeQuery("price").lte(250)); // 關聯查詢條件request.source().query(boolQuery);// 3.發送請求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析響應handleResponse(response);}//查詢后排序和按頁查詢 el的分頁查詢是查詢所有結果之后再分頁。@Testvoid testpageandsort() throws IOException { // 頁碼,每頁大小int pagenum = 1, pagesize = 5;// 1.準備RequestSearchRequest request = new SearchRequest("hotel");request.source().query(QueryBuilders.matchAllQuery());request.source().sort("price", SortOrder.ASC); // 前端傳過來的是頁碼和每頁大小 ,算一下從第多少條后開始分頁request.source().from((pagenum - 1) * pagesize); // 頁大小request.source().size(pagesize);// 3.發送請求SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 4.解析響應handleResponse(response);}//查詢后高亮顯示@Testvoid testhightlight() throws IOException {// 1.準備RequestSearchRequest request = new SearchRequest("hotel");request.source().query(QueryBuilders.matchQuery("brand", "如家")); // requireFieldMatch(false) 搜索條件brand和高亮的屬性name設為不一致request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));// 3.發送請求SearchResponse response = client.search(request, RequestOptions.DEFAULT);handleHeightLightResponse(response);}// 高亮查詢private void handleHeightLightResponse(SearchResponse response) {// 4.解析響應SearchHits searchHits = response.getHits();// 4.1.獲取總條數long total = searchHits.getTotalHits().value;System.out.println("共搜索到" + total + "條數據");// 4.2.文檔數組SearchHit[] hits = searchHits.getHits();// 4.3.遍歷for (SearchHit hit : hits) {// 獲取文檔sourceString json = hit.getSourceAsString();// 反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class); // 獲取高亮Map<String, HighlightField> highlightFields = hit.getHighlightFields();HighlightField highlightField = highlightFields.get("name");String name = highlightField.getFragments()[0].toString();hotelDoc.setName(name);System.out.println(hotelDoc);}} // 解析響應函數private void handleResponse(SearchResponse response) {// 4.解析響應SearchHits searchHits = response.getHits();// 4.1.獲取總條數long total = searchHits.getTotalHits().value;System.out.println("共搜索到" + total + "條數據");// 4.2.文檔數組SearchHit[] hits = searchHits.getHits();// 4.3.遍歷for (SearchHit hit : hits) {// 獲取文檔sourceString json = hit.getSourceAsString();// 反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class); // System.out.println("hotelDoc = " + hotelDoc);}}@BeforeEachvoid setup() {this.client =new RestHighLevelClient(RestClient.builder(HttpHost.create("http://101.43.94.150:9200")));}@AfterEachvoid shutdown() throws IOException {this.client.close();} }總結
以上是生活随笔為你收集整理的RestClient 访问elasticsearch的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 轮子王-原创数据结构-V2.0--内存/
- 下一篇: 物联网助力智慧农业