博客
关于我
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备份工具xtrabackup
    查看>>
    mysql备份恢复出错_尝试备份/恢复mysql数据库时出错
    查看>>
    mysql复制内容到一张新表
    查看>>
    mysql复制表结构和数据
    查看>>
    mysql复杂查询,优质题目
    查看>>
    MySQL外键约束
    查看>>
    MySQL多表关联on和where速度对比实测谁更快
    查看>>
    MySQL多表左右连接查询
    查看>>
    mysql大批量删除(修改)The total number of locks exceeds the lock table size 错误的解决办法
    查看>>
    mysql如何做到存在就更新不存就插入_MySQL 索引及优化实战(二)
    查看>>
    mysql如何删除数据表,被关联的数据表如何删除呢
    查看>>
    MySQL如何实现ACID ?
    查看>>
    mysql如何记录数据库响应时间
    查看>>
    MySQL子查询
    查看>>
    Mysql字段、索引操作
    查看>>
    mysql字段的细节(查询自定义的字段[意义-行列转置];UNION ALL;case-when)
    查看>>
    mysql字段类型不一致导致的索引失效
    查看>>
    mysql字段类型介绍
    查看>>
    mysql字段解析逗号分割_MySQL逗号分割字段的行列转换技巧
    查看>>
    MySQL字符集与排序规则
    查看>>