博客
关于我
ElasticSearch - 基于 JavaRestClient 操作索引库和文档
阅读量:788 次
发布时间: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/

    你可能感兴趣的文章
    pycharm如何设置(错误、警告类的标准提醒)
    查看>>
    python入门到秃顶(10):异常
    查看>>
    百度背景换肤案例
    查看>>
    输出对象的值——踩坑
    查看>>
    在苹果Mac上如何更改AirDrop名称?
    查看>>
    springboot redis key乱码
    查看>>
    idea thymeleaf页面变量报错解决
    查看>>
    wxwidgets自定义事件+调试
    查看>>
    Unable to run Intel® HAXM installer: 无法启动过程,工作目录
    查看>>
    Vue.js学习-15-v-for循环数组内容
    查看>>
    kafka超时错误或者发送消息失败等错误,排错方式
    查看>>
    sockjs-node/info?t=1462183700002 报错解决方案
    查看>>
    Latex 错误集合
    查看>>
    浏览器打开winscp 系统错误。代码:5。 拒绝访问。
    查看>>
    Kubernetes 无法查询到并且无法删除pod实例的排查过程
    查看>>
    android中button修改不了背景颜色
    查看>>
    github 入门
    查看>>
    温故知新,.Net Core遇见Consul(HashiCorp),实践分布式服务注册与发现
    查看>>
    HTML 表单验证
    查看>>
    python解释器环境问题
    查看>>