0
点赞
收藏
分享

微信扫一扫

ElasticSearch的基本操作第一章

Hyggelook 2022-04-01 阅读 65

分布式搜索引擎ElasticSearch

ElasticSearch的DSL基本操作

mapping映射属性

mapping是对索引库中文档的约束,常见的mapping属性包括:

  • type:字段数据类型,常见的简单类型有:
    • 字符串:text(可分词的文本)、keyword(精确值,例如:品牌、国家、ip地址)
    • 数值:long、integer、short、byte、double、float、
    • 布尔:boolean
    • 日期:date
    • 对象:object
  • index:是否创建倒排索引,默认为true
  • analyzer:使用哪种分词器,安装ik分词器插件之后,会多出一下两种模式
    • ik_smart:智能切分,粗粒度(例如:Java程序员——>Java,程序员)
    • ik_max_word:最细切分,细粒度(例如:Java程序员——>Java,程序员,程序,员)
  • properties:该字段的子字段

索引库操作

  • 创建索引库:PUT /索引库名
  • 查询索引库:GET /索引库名
  • 删除索引库:DELETE /索引库名
  • 添加字段:PUT /索引库名/_mapping

文档操作

  • 创建文档:POST /{索引库名}/_doc/文档id { json文档 }
 PUT /softeem
 {
   "mappings": {
       "properties": {
          "info":{
             "type": "text",
             "analyzer": "ik_smart"
          },
          "email":{
            "type": "keyword",
            "index": false
          },
          "name":{
             "type":"object",
              "properties": {
                "firstName": {
                   "type":"keyword",
                  "index": false
                },
                 "lastName": {
                   "type":"keyword",
                  "index": false
                }
              }
          }
       }
   }
 }
  • 查询文档:GET /{索引库名}/_doc/文档id
  • 删除文档:DELETE /{索引库名}/_doc/文档id
  • 修改文档:
    • 全量修改(直接覆盖原来的文档):PUT /{索引库名}/_doc/文档id { json文档 }
      语法
PUT /{索引库名}/_doc/文档id
{
    "字段1": "值1",
    "字段2": "值2",
    // ... 略
}
  • 增量修改(修改文档中的部分字段):POST /{索引库名}/_update/文档id { “doc”: {字段}}
    语法
POST /{索引库名}/_update/文档id
{
    "doc": {
         "字段名": "新的值",
    }
}

理解——对应关系

索引库——数据库的表
一个文档——表中的一条记录

RestAPI——创建索引库和RestClient操作文档

实例代码

package com.softeem.hotel;

import com.alibaba.fastjson.JSON;
import com.softeem.hotel.pojo.Hotel;
import com.softeem.hotel.pojo.HotelDoc;
import com.softeem.hotel.service.IHotelService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

import static com.softeem.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

@SpringBootTest
class HotelDemoApplicationTests {
    private RestHighLevelClient client;
    @Autowired
    private IHotelService iHotelService;

    @BeforeEach
    void setUp(){
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.245.102:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException{
        this.client.close();
    }

    //创建索引库
    @Test
    void test01() throws IOException {
        //创建请求对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //请求参数
        //这里的MAPPING_TEMPLATE是自己定义的常量字符串,是DSL语句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //发起请求
        //IndicesClient对象封装了所有与索引库操作有关的方法
        IndicesClient indices = this.client.indices();
        indices.create(request, RequestOptions.DEFAULT);
    }

    //删除索引库
    @Test
    void test02() throws IOException {
        //创建请求对象,参数为索引库名
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        //请求参数,无
        //发送请求
        client.indices().delete(request,RequestOptions.DEFAULT);
    }

    //判断索引库是否存在,本质是查询
    @Test
    void test03() throws IOException {
        //创建请求对象
        GetIndexRequest request = new GetIndexRequest("hotel");
        //发送请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists?"存在":"不存在");

    }

    //新增文档
    @Test
    void test04() throws IOException {
        //数据库
        //查询id为38665的数据
        Hotel hotel = iHotelService.getById(38665L);
        //转换为文档
        HotelDoc hotelDoc = new HotelDoc(hotel);
        //文档转换为json
        String jsonString = JSON.toJSONString(hotelDoc);

        //elasticsearch
        //创建请求对象
        IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
        //请求参数
        request.source(jsonString,XContentType.JSON);
        //发送请求
        client.index(request,RequestOptions.DEFAULT);
    }

    //查询文档
    @Test
    void test05() throws IOException {
        //创建请求对象
        GetRequest request = new GetRequest("hotel", String.valueOf(38665));
        //发送请求
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //解析响应对象
        String sourceAsString = response.getSourceAsString();

        HotelDoc hotelDoc = JSON.parseObject(sourceAsString, HotelDoc.class);
        System.out.println(hotelDoc);
        System.out.println(sourceAsString);
    }

    //删除文档
    @Test
    void test06() throws IOException {
        //创建请求对象
        DeleteRequest request = new DeleteRequest("hotel", "38665");
        //发送请求
        client.delete(request,RequestOptions.DEFAULT);
    }

    /**
     * 修改文档
     *  全量修改:本质是先根据id删除,再新增
     *  增量修改:修改文档中的指定字段值
     *  如果新增时,ID已经存在,则修改
     *  如果新增时,ID不存在,则新增
     */
    @Test
    void test07() throws IOException {
        //创建请求对象
        UpdateRequest request = new UpdateRequest("hotel", "38665");
        //请求参数
        request.doc("price","952",
                "starName","四钻");
        //发送请求
        client.update(request,RequestOptions.DEFAULT);
    }

    //批量导入文档
    @Test
    void test08() throws IOException {
        //mysql查询所有数据
        List<Hotel> list = iHotelService.list();
        //1.创建Bulk对象
        BulkRequest bulkRequest = new BulkRequest();
        //2.添加新增文档的请求
        for (Hotel hotel : list) {
            //创建新增文档请求,id可自己指定,不指定随机生成
            HotelDoc hotelDoc = new HotelDoc(hotel);
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
            //添加新增文档的请求
            bulkRequest.add(request);
        }
        //3.发送请求
        client.bulk(bulkRequest,RequestOptions.DEFAULT);
    }
}

小结

  • 索引库操作的基本步骤
    • 初始化RestHighLevelClient
    • 创建XxxIndexRequest。XXX是Create、Get、Delete
    • 准备DSL( Create时需要,其它是无参)
    • 发送请求。调用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete
  • 文档操作的基本步骤
    • 初始化RestHighLevelClient
    • 创建XxxRequest。XXX是Index、Get、Update、Delete、Bulk
    • 准备参数(Index、Update、Bulk时需要)
    • 发送请求。调用RestHighLevelClient#.xxx()方法,xxx是index、get、update、delete、bulk
    • 解析结果(Get时需要)
举报

相关推荐

0 条评论