😊 @ 作者: 瓶盖子io
💖 @ 主页: 瓶盖子io-CSDN博客
<properties> <java.version>1.8</java.version> <!--指定版本--> <elasticsearch.version>7.4.0</elasticsearch.version> </properties>
<!--elasticsearch--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.4.0</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>7.4.0</version> </dependency> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.4.0</version> </dependency>
如果是使用boot的template
<!--ES--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> </dependency>
索引库操作
创建索引库及mapping
private RestHighLevelClient client;
文档操作
Code
@SpringBootTest class HotelIndexTests { private RestHighLevelClient client; @BeforeEach public void contextLoads() { //创建连接 client = new RestHighLevelClient(RestClient.builder( HttpHost.create("192.168.200.130:9200") )); } //创建索引库 @Test public void create() throws IOException { //创建请求对象 CreateIndexRequest request = new CreateIndexRequest("hotel"); //准备请求参数 request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON); //发送请求 client.indices().create(request, RequestOptions.DEFAULT); } //删除索引库 @Test public void delete() throws IOException { //创建请求对象 DeleteIndexRequest request = new DeleteIndexRequest("hotel"); client.indices().delete(request,RequestOptions.DEFAULT); } //判断索引库是否存在 @Test public void exists() throws IOException { GetIndexRequest request = new GetIndexRequest("hotel"); boolean b = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(b==true?"存在":"不存在"); } @AfterEach public void close() throws IOException { //关闭连接 client.close(); } }
DB数据到ES
Code
@SpringBootTest public class HotelDocumentTests { private RestHighLevelClient client; @Autowired private HotelService hotelService; @BeforeEach public void createClient(){ client = new RestHighLevelClient(RestClient.builder( HttpHost.create("192.168.200.130:9200") )); } //新增文档 @Test public void addDocumentTest() throws IOException { Hotel hotel = hotelService.getById(36934); HotelDoc doc = new HotelDoc(hotel); IndexRequest request = new IndexRequest("hotel").id("36934"); String json = JSON.toJSONString(doc); request.source(json, XContentType.JSON); client.index(request, RequestOptions.DEFAULT); } //查询指定文档 @Test public void selectDocumentTest() throws IOException { GetRequest request = new GetRequest("hotel","36934"); GetResponse response = client.get(request, RequestOptions.DEFAULT); System.out.println(response.getSourceAsString()); } //删除指定文档 @Test public void deleteDocumentTest() throws IOException { DeleteRequest request = new DeleteRequest("hotel").id("36934"); client.delete(request,RequestOptions.DEFAULT); } //修改文档 @Test public void updateDocumentTest() throws IOException { UpdateRequest request = new UpdateRequest("hotel","36934"); request.doc( "starName","三星", "price","358" ); client.update(request,RequestOptions.DEFAULT); } //批量导入(方式一) @Test public void batchDocumentTest_01() throws IOException { List<Hotel> hotelList = hotelService.list(); HotelDoc doc; IndexRequest request; for (Hotel hotel : hotelList) { doc = new HotelDoc(hotel); request = new IndexRequest("hotel").id(hotel.getId()+""); String docJson = JSON.toJSONString(doc); request.source(docJson,XContentType.JSON); client.index(request,RequestOptions.DEFAULT); } } //批量导入(方式二) @Test public void batchDocument_02() throws IOException { List<Hotel> hotelList = hotelService.list(); BulkRequest request = new BulkRequest(); HotelDoc doc; for (Hotel hotel : hotelList) { doc = new HotelDoc(hotel); request.add(new IndexRequest("hotel").id(hotel.getId()+"") .source(JSON.toJSONString(doc),XContentType.JSON)); } client.bulk(request,RequestOptions.DEFAULT); } @AfterEach public void close() throws IOException { client.close(); } }
查询操作
公有的方法
匹配所有字段和单个字段
范围Range
复合查询 BoolQuery
结果处理-排序,分页
高亮处理
Code
@SpringBootTest public class HotelQueryTest { private RestHighLevelClient client; @BeforeEach public void createClient(){ client = new RestHighLevelClient(RestClient.builder( HttpHost.create("192.168.200.130:9200") )); } private SearchRequest request = new SearchRequest("hotel"); //matchAll @Test public void testMatchAll() throws IOException { //构建dsl request.source().query(QueryBuilders.matchAllQuery()); SearchResponse response = client.search(request, RequestOptions.DEFAULT); //解析 this.parseResponse(response); } //match查询 @Test public void testMatch() throws IOException { //创建search对象 request.source().query(QueryBuilders.matchQuery("all","如家")); SearchResponse response = client.search(request, RequestOptions.DEFAULT); //解析响应 this.parseResponse(response); } //精确查询-词条精确匹配 @Test public void testTerm() throws IOException { request.source().query(QueryBuilders.termQuery("city","北京")); SearchResponse response = client.search(request, RequestOptions.DEFAULT); this.parseResponse(response); } //范围 @Test public void testRange() throws IOException { //大于等于99小于等于199 request.source().query(QueryBuilders.rangeQuery("price").gte(99).lte(199)); SearchResponse response = client.search(request, RequestOptions.DEFAULT); this.parseResponse(response); } //复合查询 bool @Test public void testBool() throws IOException { BoolQueryBuilder boolQuery = new BoolQueryBuilder(); //城市必须是北京 boolQuery.must(QueryBuilders.termQuery("city","北京")); //品牌可以是皇冠假日或者希尔顿 boolQuery.should(QueryBuilders.termsQuery("brand","皇冠假日","希尔顿")); //大于等于500 boolQuery.mustNot(QueryBuilders.rangeQuery("price").lte(500)); //必须匹配 boolQuery.filter(QueryBuilders.termQuery("starName","五钻")); boolQuery.filter(QueryBuilders.termQuery("score",46)); request.source().query(boolQuery); SearchResponse response = client.search(request, RequestOptions.DEFAULT); this.parseResponse(response); } //结果处理-排序,分页 @Test public void testResult() throws IOException { int page = 1; int pageSize = 5; request.source().query(QueryBuilders.matchAllQuery()); //设置分页 request.source().from((page - 1 )* pageSize).size(pageSize); //设置排序 request.source().sort("price", SortOrder.DESC); SearchResponse response = client.search(request, RequestOptions.DEFAULT); this.parseResponse(response); } //高亮 @Test public void highLight() throws IOException { request.source().query(QueryBuilders.matchQuery("name","如家")); request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false)); SearchResponse response = client.search(request, RequestOptions.DEFAULT); this.parseResponse(response); } //提取的公用的方法解析 public void parseResponse(SearchResponse response){ SearchHits searchHits = response.getHits(); long value = searchHits.getTotalHits().value; System.out.println("共搜到"+value+"条数据"); SearchHit[] hits = searchHits.getHits(); for (SearchHit hit : hits) { String json = hit.getSourceAsString(); System.out.println(json); HotelDoc doc = JSON.parseObject(json, HotelDoc.class); System.out.println(doc); Map<String, HighlightField> map = hit.getHighlightFields(); HighlightField highlightField = map.get("name"); if (highlightField != null){ String s = highlightField.getFragments()[0].toString(); System.out.println(s); } } } @AfterEach public void close() throws IOException { client.close(); } }