es对索引和文档的crud操作

使用控制台方式操作索引

创建索引,这里我们通过kibana可视化操作工具对es索引进行创建

创建语法如下:

PUT /xxx  //index名称
{
  "mappings": {
    "properties": {
      "info":{ 
        "type": "text", //类型,text:可分割字符串
        "analyzer": "ik_smart" //分词器
      },
      "email":{
        "type": "keyword", //类型,keyword:不可分割字符串
        "index": false  //是否可以作为index查找
      },
      "name":{
        "type": "object",  //对象类型,可以嵌套其他类型使用
        "properties": {
          "lastName": {
            "type": "keyword"
          },
           "firstName": {
            "type": "keyword"
          }
        }
      }
    }
  

在这里插入图片描述
获取index

GET /xxx

在这里插入图片描述

往索引中添加新的字段

PUT /XXX/_mapping
{
  "properties": {
    "phone":{
      "type": "integer"
    }
}

在这里插入图片描述

在这里插入图片描述
删除指定索引

DELETE /hubert
在这里插入图片描述

使用springboot整合es基本操作

前期配置

1.引入相关依赖


    <properties>
        <java.version>1.8</java.version>
        <!--和es版本保持一致-->
        <elasticsearch.version>7.12.1</elasticsearch.version>
    </properties>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
        

2与es相关配置

spring:
  elasticsearch:
    rest:
      uris: 192.168.184.100:9200
  data:
    elasticsearch:
      repositories:
        enabled: true

3 构建一个配置类,将RestHighLevelClient 注入容器


@Configuration
public class ESClientConfig {

    @Value("${spring.elasticsearch.rest.uris}")
    private String uris;

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration configuration = ClientConfiguration.builder()
                .connectedTo(uris)
                .build();
        return RestClients.create(configuration).rest();
    }

}

具体使用

1 操作索引

首先通过
@Autowired
private RestHighLevelClient restHighLevelClient;
把client对象注入

   /**
     * 创建hotel表对应es索引
     * @throws IOException
     */
    @Test
    public void createIndex() throws IOException {
        //创建requst对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //设置源
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //发送请求
        restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
    }

这里的 MAPPING_TEMPLATE是定义在常量类中的一个常量,里面的数据结构和数据表中的结构对应。其实就是构建index的语法。通过json的方式把构建语句发送到es服务端,然后服务端构建。

public final static String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_smart\"\n" +
            "      },\n" +
            "      \"price\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"score\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"starName\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\":{\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";

在这里插入图片描述
删除和获取比较简单,如下代码所示:

 //删除索引
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest hotel = new DeleteIndexRequest("hotel");
        restHighLevelClient.indices().delete(hotel,RequestOptions.DEFAULT);
    }
    //获取索引
    @Test
    public void editIndex() throws IOException {
        GetIndexRequest hotel = new GetIndexRequest("hotel");
        GetIndexResponse res = restHighLevelClient.indices().get(hotel, RequestOptions.DEFAULT);
        String[] indices = res.getIndices();
        for (int i = 0; i < indices.length; i++) {
            String index = indices[i];
            System.out.println(index);
        }
    }

索引无法被修改。

2 操作doc文档

首先还是将client注入
@Autowired
private RestHighLevelClient restHighLevelClient;

然后创建出对应索引的文档:

    /**
     * 创建索引库对应文档
     */
    @Test
    public void createDoc() throws IOException {
        //从数据库中获取文档数据
        Hotel h = iHotelService.getById(36934);
        HotelDoc hotelDoc = new HotelDoc(h);
        //根据id获取doc需要的request对象
        IndexRequest request = new IndexRequest("hotel").id(h.getId().toString());
        //填写需要构建的数据
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //发送请求
        restHighLevelClient.index(request,RequestOptions.DEFAULT);
    }

这里的数据是通过mybatispuls在数据库中查出的。hoetlDoc对象是因为在es中,坐标是一对经纬度数据对应的值,而数据库中存储的是经度和纬度。在构建对象的时候转换了一下。

this.location = hotel.getLatitude() + ", " + hotel.getLongitude();

也是通过json数据发送到es服务端创建。

查询操作是通过index名和doc id查询

    /**
     * 根据id和index查询doc数据
     * @throws IOException
     */
    @Test
    public void getDoc() throws IOException {
        GetRequest request = new GetRequest("hotel", "36934");
        GetResponse fields = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        String sourceAsString = fields.getSourceAsString();
        HotelDoc parse = JSON.parseObject(sourceAsString,HotelDoc.class);
        System.out.println(parse);
    }

更新操作中,doc对象的书写语法和json不同,需要注意

   /**
     * 更新
     * @throws IOException
     */
    @Test
    public void updateDoc() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("hotel", "36934");
        //设置要更新的字段
        updateRequest.doc(
                "brand","8天酒店",
                "city","武汉"
        );
        restHighLevelClient.update(updateRequest,RequestOptions.DEFAULT);
    }

删除非常简单,也是通过index名和doc id确定删除对象

   /**
     * 删除
     * @throws IOException
     */
    @Test
    public void deleteDoc() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("hotel", "36934");
        restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
    }

批处理,需要构建一个bulk对象用于批量处理新增,修改,删除等操作,就是在reques中添加相应的其他reques,然后其他一样。这里构建的是新增的request,用于批量新增。

    /**
     * 实现对数据的批量添加
     * @throws IOException
     */
    @Test
    public void batchCreateDoc() throws IOException {
        //构建bulkrequest对象
        BulkRequest bulkRequest = new BulkRequest();
        //查询数据信息
        List<Hotel> list = iHotelService.list();
        for (Hotel hotel : list) {
            HotelDoc hotelDoc = new HotelDoc(hotel);
            bulkRequest.add(new IndexRequest("hotel1")
                    .id(hotel.getId().toString())
                    .source(JSON.toJSONString(hotelDoc),XContentType.JSON));
        }
        //发送bulk请求批量处理数据
        restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
    }
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值