编辑
2025-10-02
java
00

目录

1.什么是RestClient
2.实现RestClient案例
3.文档的增删改查
4.文档的批量导入功能
5.elasticsearch搜索功能

1.什么是RestClient

image.png

2.实现RestClient案例

导入数据库 image.png 编写创建索引库的语句

image.png

image.png

使用copy_to可以将当前的字段拷贝到其他之中实现同时根据多个字段搜索

DSL
# 酒店的mappings PUT /hotel { "mappings": { "properties": { "id":{ "type":"keyword" }, "name":{ "type": "text", "analyzer": "ik_max_word", "copy_to": "all" }, "address":{ "type": "keyword", "index": false }, "price":{ "type": "integer" }, "score":{ "type": "integer" }, "brand":{ "type": "keyword", "copy_to": "all" },"city":{ "type": "keyword" },"starName":{ "type": "keyword" },"business":{ "type": "keyword", "copy_to": "all" }, "location":{ "type": "geo_point" }, "pic":{ "type": "keyword", "index": false } ,"all":{ "type": "text", "analyzer": "ik_max_word" } } } }

初始化项目中的RestClient

image.png

pom
<!-- elasticsearch--> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.12.1</version> </dependency>

springboot管理了elasticsearch的版本需要添加覆盖版本 image.png 覆盖版本 image.png 版本全部变为7.12.1(与搭建的elasticsearch一致) image.png 在测试类中编写初始化和销毁代码

java
ublic class HotelIndexTest { private RestHighLevelClient client; @BeforeEach void setUp(){ this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.42.10:9200"))) } @AfterEach void tearDown() throws IOException { this.client.close(); } }

编写创建索引库代码 image.png

java
@Test void testCreateHotelIndex() throws IOException { // 创建request对象 CreateIndexRequest request = new CreateIndexRequest("hotel"); // 请求参数 request.source(MAPPING_TEMPLATE, XContentType.JSON); // 发起请求 client.indices().create(request, RequestOptions.DEFAULT); }

编写一个类存放创建索引库的语句

java
package cn.itcast.hotel.constants; public class HotelConstants { public final static 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" + " },\"city\":{\n" + " \"type\": \"keyword\"\n" + " },\"starName\":{\n" + " \"type\": \"keyword\"\n" + " },\"business\":{\n" + " \"type\": \"keyword\",\n" + " \"copy_to\": \"all\"\n" + " },\n" + " \"location\":{\n" + " \"type\": \"geo_point\"\n" + " },\n" + " \"pic\":{\n" + " \"type\": \"keyword\",\n" + " \"index\": false\n" + " \n" + " }\n" + " ,\"all\":{\n" + " \"type\": \"text\",\n" + " \"analyzer\": \"ik_max_word\"\n" + " }\n" + " }\n" + " }\n" + "}"; }

运行代码查询平台创建成功

java
{ "hotel" : { "aliases" : { }, "mappings" : { "properties" : { "address" : { "type" : "keyword", "index" : false }, "brand" : { "type" : "keyword" }, "business" : { "type" : "keyword" }, "city" : { "type" : "keyword" }, "id" : { "type" : "keyword" }, "location" : { "type" : "geo_point" }, "name" : { "type" : "text", "analyzer" : "ik_max_word" }, "pic" : { "type" : "keyword", "index" : false }, "price" : { "type" : "integer" }, "score" : { "type" : "integer" }, "starName" : { "type" : "keyword" } } }, "settings" : { "index" : { "routing" : { "allocation" : { "include" : { "_tier_preference" : "data_content" } } }, "number_of_shards" : "1", "provided_name" : "hotel", "creation_date" : "1759399676974", "number_of_replicas" : "1", "uuid" : "aRnUh_l1Thi3hABSvrbm_w", "version" : { "created" : "7120199" } } } } }

删除索引库判断索引库是否存在

image.png

java
@Test void testGetHotelIndex() throws IOException { // 创建request对象 GetIndexRequest request = new GetIndexRequest("hotel"); // 发起判断索引库是否存在 boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); // 输出结果 System.out.println(exists); }
java
@Test void testDeleteHotelIndex() throws IOException { // 创建request对象 DeleteIndexRequest request = new DeleteIndexRequest("hotel"); // 发起删除请求 client.indices().delete(request, RequestOptions.DEFAULT); }

3.文档的增删改查

编写添加文档代码

java
@Test void testInsertIndex() throws IOException { // 根据id查询hotel数据 Hotel hotel= hotelService.getById(36934L); // 将hotel转成hotelDoc HotelDoc hotelDoc = new HotelDoc(hotel); // 创建request对象 IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString()); request.source(JSON.toJSONString(hotelDoc),XContentType.JSON); client.index(request, RequestOptions.DEFAULT); }

添加成功在可视化平台上查询 添加成功

image.png

根据id查询文档

image.png

java
@Test void testGetDocument() throws IOException { // 创建request对象 GetRequest request = new GetRequest("hotel","36934"); // 获取response GetResponse response = client.get(request, RequestOptions.DEFAULT); // 解析返回数据 String json = response.getSourceAsString(); // 打印结果 HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class); System.out.println(hotelDoc.toString()); }

修改文档

java
@Test void testUpdateDocument() throws IOException { UpdateRequest request = new UpdateRequest("hotel","36934"); request.doc("price","952","starName","四钻"); client.update(request, RequestOptions.DEFAULT); }

删除文档

java
@Test void testDeleteDocument() throws IOException { DeleteRequest request = new DeleteRequest("hotel","36934"); client.delete(request, RequestOptions.DEFAULT); }

总结

image.png

4.文档的批量导入功能

image.png

代码示例

java
@Test void testRangeIndexDocument() throws IOException { // 使用mybatis-plus读取数据库数据 List<Hotel> hotelList = hotelService.list(); BulkRequest request = new BulkRequest(); for (Hotel hotel : hotelList) { HotelDoc hotelDoc = new HotelDoc(hotel); request.add(new IndexRequest("hotel").id(hotelDoc.getId().toString()).source(JSON.toJSONString(hotelDoc),XContentType.JSON)); } client.bulk(request, RequestOptions.DEFAULT); }

5.elasticsearch搜索功能

DSL查询

image.png

基本语法 查询所有 image.png

DSL
GET /hotel/_search { "query":{ "match_all":{ } } }

全文检索查询(搜索框搜索)

image.png

image.png

使用all搜索设置好的字段

DSL
# match 单字段查询 Get /hotel/_doc/_search { "query":{ "match":{ "all":"外滩" } } }
DSL
# multi_match 多字段查询 Get /hotel/_doc/_search { "query":{ "multi_match":{ "query":"外滩如家", "fields":["brand","name","business"] } } }

精确查询

image.png

image.png

DSL
# term查询 GET /hotel/_search { "query": { "term": { "city" : { "value": "北京" } } } }

价格在 100到300(包含100 300)

DSL
# range GET /hotel/_search { "query":{ "range":{ "price":{ "gte":100, "lte":300 } } } }

价格在 1341到3000(不包含1341 3000)

DSL
GET /hotel/_search { "query":{ "range":{ "price":{ "gt":1341, "lt":3000 } } } }

地理查询

geo_bounding_box

image.png

geo_distance

image.png

DSL
GET /hotel/_search { "query":{ "geo_distance":{ "distance":"15km", "location":"31.21,121.5" } } }

复合查询

image.png

image.png

image.png

控制查询

image.png

控制品牌为如家的酒店放在最上面

DSL
# function score GET /hotel/_search { "query":{ "function_score": { "query": { "match":{ "all":"外滩" } }, "functions": [ { "filter": { "term": { "brand": "如家" } }, "weight": 100 } ], "boost_mode": "multiply" } } }

image.png

案例

image.png

DSL
GET /hotel/_search { "query":{ "bool":{ "must": [ { "match": { "name": "如家" } } ], "must_not": [ { "range": { "price": { "gt": 400 } } } ], "filter": [ { "geo_distance": { "distance": "10km", "location": { "lat": 31.21, "lon": 121.5 } } } ] } } }

在filter中的内容不参与算分降低性能消耗

本文作者:钱小杰

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!