Elasticsearch实战篇:索引库、文档与JavaRestClient操作指南

张开发
2026/4/18 5:53:08 15 分钟阅读

分享文章

Elasticsearch实战篇:索引库、文档与JavaRestClient操作指南
Elasticsearch 实战篇索引库、文档与 JavaRestClient 操作指南整理自黑马程序员《SpringCloud微服务开发与实战》Elasticsearch01 课程对应章节索引库操作、文档操作、JavaRestClient 客户端一、索引库操作 (Index Operations)索引库类似于 MySQL 中的表Mapping 定义了表结构字段类型、分词器等。1. Mapping 映射属性在创建索引库前需定义字段的 Mapping 属性。黑马课程中重点讲解了以下核心属性属性名含义常用值/示例type字段数据类型text可分词的文本,keyword精确值,integer,date,objectindex是否创建索引是否可被搜索true默认可搜索,false仅存储不可搜索如图片路径analyzer创建索引时使用的分词器ik_smart粗粒度,ik_max_word细粒度search_analyzer搜索时使用的分词器通常与analyzer保持一致如ik_smartproperties子字段定义用于嵌套对象定义对象内部的字段结构示例黑马商城商品字段 Mapping 分析{mappings:{properties:{id:{type:keyword},// 精确匹配不分词name:{type:text,analyzer:ik_max_word,// 写入时细粒度分词search_analyzer:ik_smart// 搜索时粗粒度分词},price:{type:integer},// 用于范围查询brand:{type:keyword},// 品牌做精确匹配spec:{type:object,// 规格参数对象properties:{size:{type:keyword}}}}}}2. 索引库的 CRUD操作DSL 命令说明创建PUT /索引库名需携带完整的 Mapping 结构查询GET /索引库名查看索引库的 Mapping 信息删除DELETE /索引库名删除整个索引库数据不可恢复修改PUT /索引库名/_mapping只能添加新字段不能修改已有字段ES 限制创建索引库完整示例PUT/heima_goods{mappings:{properties:{info:{type:text,analyzer:ik_smart},email:{type:keyword,index:false}// 不参与搜索}}}二、文档操作 (Document Operations)文档是索引库中的具体数据以 JSON 格式存储。1. 文档的 CRUD操作DSL 命令特点新增文档POST /索引库名/_doc/{id}指定 ID 新增查询文档GET /索引库名/_doc/{id}根据 ID 查询单条删除文档DELETE /索引库名/_doc/{id}物理删除全量修改PUT /索引库名/_doc/{id}覆盖更新先删除后新增版本号1增量修改POST /索引库名/_update/{id}只修改指定字段使用doc包裹增量修改示例POST/heima_goods/_update/1{doc:{price:2999// 仅修改价格字段}}2. 批量操作 (Bulk API)用于高性能地批量新增、修改或删除文档。黑马项目中常用于数据初始化如导入酒店数据。DSL 格式注意是POST请求操作类型与数据成对出现POST/_bulk{index:{_index:hotel,_id:1}}{name:如家酒店,price:300}{index:{_index:hotel,_id:2}}{name:汉庭酒店,price:400}三、JavaRestClient 客户端ES 官方提供的 Java 高级客户端用于在代码中替代 Kibana 的 DSL 语句。1. 环境初始化步骤 1引入依赖注意版本对齐dependencygroupIdorg.elasticsearch.client/groupIdartifactIdelasticsearch-rest-high-level-client/artifactId/dependency!-- 覆盖 Spring Boot 默认的 ES 版本 --propertieselasticsearch.version7.12.1/elasticsearch.version/properties步骤 2配置客户端 BeanConfigurationpublicclassElasticsearchConfig{BeanpublicRestHighLevelClientrestHighLevelClient(){returnnewRestHighLevelClient(RestClient.builder(HttpHost.create(http://你的IP:9200)));}}2. 索引库操作 (Java API)核心对象IndicesClient通过client.indices()获取操作请求类关键代码创建索引CreateIndexRequestclient.indices().create(request, RequestOptions.DEFAULT)删除索引DeleteIndexRequestclient.indices().delete(request, RequestOptions.DEFAULT)判断存在GetIndexRequestclient.indices().exists(request, RequestOptions.DEFAULT)创建索引库代码示例TestvoidtestCreateIndex()throwsIOException{// 1. 创建 Request 对象CreateIndexRequestrequestnewCreateIndexRequest(hotel);// 2. 准备 DSLMAPPING_TEMPLATE 是定义好的 JSON 字符串request.source(MAPPING_TEMPLATE,XContentType.JSON);// 3. 发送请求CreateIndexResponseresponseclient.indices().create(request,RequestOptions.DEFAULT);System.out.println(response.isAcknowledged());}3. 文档操作 (Java API)核心对象直接使用RestHighLevelClient的方法。操作请求类关键方法新增/全改IndexRequestclient.index(request, ...)查询GetRequestclient.get(request, ...)删除DeleteRequestclient.delete(request, ...)增量修改UpdateRequestclient.update(request, ...)新增文档代码示例TestvoidtestAddDocument()throwsIOException{// 1. 查询数据库数据黑马案例Hotel - HotelDocHotelhotelhotelService.getById(1L);HotelDochotelDocnewHotelDoc(hotel);// 转换为文档对象// 2. 创建 Request 对象指定索引库和IDIndexRequestrequestnewIndexRequest(hotel).id(hotelDoc.getId().toString());// 3. 准备 JSON 数据使用 FastJSON 等工具转换request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);// 4. 发送请求client.index(request,RequestOptions.DEFAULT);}4. 批量导入 (BulkProcessor)黑马项目中用于一次性导入大量数据如全量商品数据。代码模板TestvoidtestBulk()throwsIOException{// 1. 查询所有数据ListHotelhotelshotelService.list();// 2. 创建批量请求BulkRequestbulkRequestnewBulkRequest();// 3. 遍历添加子请求for(Hotelhotel:hotels){HotelDocdocnewHotelDoc(hotel);IndexRequestrequestnewIndexRequest(hotel).id(doc.getId().toString()).source(JSON.toJSONString(doc),XContentType.JSON);bulkRequest.add(request);}// 4. 发送批量请求BulkResponseresponseclient.bulk(bulkRequest,RequestOptions.DEFAULT);}四、黑马商城业务改造实战1. 商品搜索改造思路数据同步商品上架时通过 JavaRestClient 将商品数据写入 ES 索引库item_index。字段设计title商品名type: text, analyzer: ik_max_wordcategory分类type: keyword用于精确过滤price价格type: integer用于范围查询specs规格type: object嵌套对象用于参数搜索搜索流程前端搜索词 - JavaRestClient 构建 DSL 查询 - 返回结果。2. 避坑指南版本一致性Spring Boot 父工程默认的 ES 客户端版本可能与服务器不一致必须在pom.xml中显式指定elasticsearch.version7.12.1/elasticsearch.version。字段不可变Mapping 中的字段一旦创建只能新增不能修改类型。设计初期需谨慎。分词器选择搜索建议用ik_smart粗粒度减少噪音索引建议用ik_max_word细粒度召回率高。

更多文章