博客
关于我
ElasticSearch - 基于 JavaRestClient 操作索引库和文档
阅读量:800 次
发布时间:2023-01-24

本文共 5192 字,大约阅读时间需要 17 分钟。

一、RestClient操作索引库

1.1 RestClient是什么?

RestClient 实际上是 Elasticsearch 官方为不同语言提供的客户端之一。作为 Java 开发人员,在进行 Elasticsearch 操作时,RestHighLevelClient 是一个非常重要的工具。

1.1.1RestClient的作用

RestClient 的主要职责是帮助我们组装 Elasticsearch 的 DSL 语句,并将请求发送到 Elasticsearch 服务器。我们只需要在 Java 代码中配置正确的参数,RestClient 将自动处理请求的发送和数据的格式化。

1.1.2如何引入RestClient依赖

在项目中引入 Elasticsearch 的 RestHighLevelClient ,需要添加以下依赖:

org.elasticsearch.client
elasticsearch-rest-high-level-client

2.1.2初始化RestClient

在项目中进行以下步骤即可初始化 RestHighLevelClient:

  • 在 pom.xml 中添加 Elasticsearch 版本信息:
  • 1.8
    7.12.1
    1. 在测试类中初始化客户端:
    2. @SpringBootTestpublic class HotelIndexTest {    private RestHighLevelClient client;    @BeforeEach    public void setUp() {        client = new RestHighLevelClient(RestClient.builder(                HttpHost.create("http://云服务器ip:9200"))        );    }    @AfterEach    public void tearDown() throws IOException {        client.close();    }}

      1.2 JavaRestClient操作索引库

      1.2.1索引库的创建

      根据酒店表结构,创建索引库时需要注意以下几点:

    3. 字段类型:id 忽略不计,默认为 keyword,不需要分词。
    4. 搜索和分词:name、address、brand、city、star_name、business 需要分词,copy_to "all"。
    5. 地理位置:location 使用 geo_point 类型。
    6. 图片:pic 不能分词,直接设置为 keyword
    7. 自定义映射:将 name、address、brand 等字段拷贝到 "all" 字段。
    8. 索引库的创建 DSL 语句如下:

      {    "mappings": {        "properties": {            "id": {                "type": "keyword"            },            "name": {                "type": "text",                "analyzer": "ik_max_word",                "copy_to": "all"            },            "address": {                "type": "text",                "analyzer": "ik_max_word",                "copy_to": "all"            },            "price": {                "type": "integer"            },            "score": {                "type": "integer"            },            "brand": {                "type": "keyword",                "copy_to": "all"            },            "city": {                "type": "keyword",                "copy_to": "all"            },            "star_name": {                "type": "keyword"            },            "business": {                "type": "keyword",                "copy_to": "all"            },            "location": {                "type": "geo_point"            },            "all": {                "type": "text",                "analyzer": "ik_max_word"            }        }    }}

      创建索引库的代码示例:

      @Testpublic void testCreateHotelIndex() throws IOException {    CreateIndexRequest request = new CreateIndexRequest("hotel");    request.source(MAPPING_TEMPLATE, XContentType.JSON);    client.indices().create(request, RequestOptions.DEFAULT);}

      1.2.2判断索引库是否存在

      检查索引库是否存在的代码如下:

      @Testpublic void testExistsHotelIndex() throws IOException {    GetIndexRequest request = new GetIndexRequest("hotel");    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);    System.out.println(exists);}

      1.2.3删除索引库

      删除索引库的代码:

      @Testpublic void testDeleteHotelIndex() throws IOException {    DeleteIndexRequest request = new DeleteIndexRequest("hotel");    client.indices().delete(request, RequestOptions.DEFAULT);}

      1.3 JavaRestClient文档CRUD操作

      1.3.1初始化

      与创建索引库的初始化步骤相同,代码如下:

      @SpringBootTestpublic class HotelDocumentTest {    private RestHighLevelClient client;    @BeforeEach    public void setUp() {        client = new RestHighLevelClient(RestClient.builder(                HttpHost.create("http://云服务器ip:9200"))        );    }    @AfterEach    public void tearDown() throws IOException {        client.close();    }}

      1.3.2添加文档

      将数据库中的酒店数据转化为 Elasticsearch 文档,并添加到索引库中。代码示例如下:

      @Testpublic void testAddDocument() throws IOException {    Hotel hotel = hotelService.getById(5865979L);    HotelDoc hotelDoc = new HotelDoc(hotel);    String hotelJson = objectMapper.writeValueAsString(hotelDoc);    IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());    request.source(hotelJson, XContentType.JSON);    client.index(request, RequestOptions.DEFAULT);}

      1.3.3根据 id 查询文档

      查询文档的代码:

      @Testpublic void testGetDocument() throws IOException {    GetRequest request = new GetRequest("hotel").id("5865979");    GetResponse response = client.get(request, RequestOptions.DEFAULT);    String json = response.getSourceAsString();    System.out.println(json);}

      1.3.4根据 id 修改文档

      全量更新文档的代码:

      @Testpublic void testUpdateDocument() throws IOException {    UpdateRequest request = new UpdateRequest("hotel", "5865979");    request.doc(        "name", "地表最强酒店",        "price", "99999"    );    client.update(request, RequestOptions.DEFAULT);}

      1.3.5根据 id 删除文档

      删除文档的代码:

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

      1.3.6批量导入文档

      批量导入酒店数据的代码:

      @Testpublic void testBulkDocument() throws IOException {    List
      hotelList = hotelService.list(); BulkRequest request = new BulkRequest(); for (Hotel hotel : hotelList) { HotelDoc hotelDoc = new HotelDoc(hotel); String json = objectMapper.writeValueAsString(hotelDoc); request.add(new IndexRequest("hotel").id(hotel.getId().toString()).source(json, XContentType.JSON)); } client.bulk(request, RequestOptions.DEFAULT);}

    转载地址:http://rheyk.baihongyu.com/

    你可能感兴趣的文章
    MySQL
    查看>>
    mysql
    查看>>
    MTK Android 如何获取系统权限
    查看>>
    MySQL - 4种基本索引、聚簇索引和非聚索引、索引失效情况、SQL 优化
    查看>>
    MySQL - ERROR 1406
    查看>>
    mysql - 视图
    查看>>
    MySQL - 解读MySQL事务与锁机制
    查看>>
    MTTR、MTBF、MTTF的大白话理解
    查看>>
    mt_rand
    查看>>
    mysql -存储过程
    查看>>
    mysql /*! 50100 ... */ 条件编译
    查看>>
    mysql 1045解决方法
    查看>>
    mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
    查看>>
    mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
    查看>>
    mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
    查看>>
    mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
    查看>>
    mui折叠面板点击事件跳转
    查看>>
    MySQL 8 公用表表达式(CTE)—— WITH关键字深入用法
    查看>>
    mysql 8 远程方位_mysql 8 远程连接注意事项
    查看>>
    MUI框架里的ajax的三种方法
    查看>>