ElasticSearch(10)通过javaAPI操作索引、操作文档

1 项目环境准备

springboot整合es:项目代码说明

2 操作索引

2.1 添加索引

只是添加索引,不指定mapping这些

package com.yy.esdemo;

import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
class EsDemoApplicationTests {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 添加索引
     */
    @Test
    public void addIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        //2.具体操作,获取返回值
        CreateIndexRequest createIndex = new CreateIndexRequest("test1");
        CreateIndexResponse createIndexResponse = indicesClient.create(createIndex,RequestOptions.DEFAULT);
        //3.根据返回值判断结果
        System.out.println(createIndexResponse.isAcknowledged());

    }

}

运行结果:
在这里插入图片描述

在添加索引时,指定mapping等信息

 @Test
    public void addIndexAndMapping() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        //2.具体操作,获取返回值
        CreateIndexRequest createIndex = new CreateIndexRequest("test2");
        //设置mapping
        String mapping = "{\n" +
                "      \"properties\" : {\n" +
                "        \"address\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\" : \"ik_max_word\"\n" +
                "        },\n" +
                "        \"age\" : {\n" +
                "          \"type\" : \"integer\"\n" +
                "        },\n" +
                "        \"name\" : {\n" +
                "          \"type\" : \"keyword\"\n" +
                "        }\n" +
                "      }\n" +
                "    }";
        createIndex.mapping("_doc",mapping, XContentType.JSON);

        CreateIndexResponse response = indicesClient.create(createIndex, RequestOptions.DEFAULT);

        //3.根据返回值判断结果
        System.out.println(response.isAcknowledged());

    }

运行结果:
在这里插入图片描述

在这里插入图片描述

2.2 查询索引

@Test
    public void queryIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        GetIndexRequest getIndexRequest = new GetIndexRequest("test2");
        GetIndexResponse response = indicesClient.get(getIndexRequest, RequestOptions.DEFAULT);

        //获取结果
        Map<String, MappingMetaData> mappings = response.getMappings();
        for (String key:mappings.keySet()){
            System.out.println(key+":"+mappings.get(key).getSourceAsMap());
        }
    }

在这里插入图片描述

2.3 删除索引

@Test
    public void deleteIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        DeleteIndexRequest deleteRequest = new DeleteIndexRequest("test1");
        AcknowledgedResponse response = indicesClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

在这里插入图片描述

2.4 判断索引是否存在

@Test
    public void existIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        GetIndexRequest getIndexRequest = new GetIndexRequest("test1");
        boolean exists = indicesClient.exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);

    }

在这里插入图片描述

3 操作文档

3.1 添加文档

map数据

@Test
    public void addDoc() throws IOException {
        //数据对象,map
        Map data = new HashMap<>();
        data.put("address","北京大三");
        data.put("name","大三");
        data.put("age",29);
        //1 获取操作文档的对象
        IndexRequest request = new IndexRequest("test2").id("1").source(data);
        //添加数据,获取返回的结果
        IndexResponse re = client.index(request, RequestOptions.DEFAULT);
        System.out.println(re.getId());
 
    }

在这里插入图片描述

通过类进行文档的添加

public class Person {
    private String id;
    private String name;
    private int age;
    private String address;
    ...
}

添加json转换的坐标

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.4</version>
        </dependency>
@Test
    public void addDoc1() throws IOException {
        //数据对象,java对象
        Person person = new Person();
        person.setId("2");
        person.setName("大四");
        person.setAddress("台湾省");
        person.setAge(123);
        //将对象转为json
        String data = JSON.toJSONString(person);

        //1 获取操作文档的对象
        IndexRequest request = new IndexRequest("test2").id(person.getId()).source(data,XContentType.JSON);
        //添加数据,获取返回的结果
        IndexResponse re = client.index(request, RequestOptions.DEFAULT);
        System.out.println(re.getId());
    }

在这里插入图片描述

3.2 修改文档

修改文档:添加文档时,如果id存在则修改,id不存在则添加

3.3 根据id查询文档

@Test
    public void queryDocById() throws IOException {
        GetRequest getRequest = new GetRequest("test2","1");
        //或者是
//        getRequest.id("1");
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);

        //获取数据对应的json数据
        System.out.println(response.getSourceAsString());
    }

在这里插入图片描述

3.4 删除文档

@Test
    public void delDoc() throws IOException {

        DeleteRequest deleteRequest = new DeleteRequest("test2","1");
        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.getId());
    }

在这里插入图片描述

4 测试代码汇总

package com.yy.esdemo;

import com.alibaba.fastjson.JSON;
import com.yy.esdemo.domain.Person;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
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.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.xcontent.XContentType;
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.HashMap;
import java.util.Map;

@SpringBootTest
class EsDemoApplicationTests {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 添加索引
     */
    @Test
    public void addIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        //2.具体操作,获取返回值
        CreateIndexRequest createIndex = new CreateIndexRequest("test1");
        CreateIndexResponse createIndexResponse = indicesClient.create(createIndex,RequestOptions.DEFAULT);
        //3.根据返回值判断结果
        System.out.println(createIndexResponse.isAcknowledged());

    }
    @Test
    public void addIndexAndMapping() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        //2.具体操作,获取返回值
        CreateIndexRequest createIndex = new CreateIndexRequest("test2");
        //设置mapping
        String mapping = "{\n" +
                "      \"properties\" : {\n" +
                "        \"address\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\" : \"ik_max_word\"\n" +
                "        },\n" +
                "        \"age\" : {\n" +
                "          \"type\" : \"integer\"\n" +
                "        },\n" +
                "        \"name\" : {\n" +
                "          \"type\" : \"keyword\"\n" +
                "        }\n" +
                "      }\n" +
                "    }";
        createIndex.mapping("_doc",mapping, XContentType.JSON);

        CreateIndexResponse response = indicesClient.create(createIndex, RequestOptions.DEFAULT);

        //3.根据返回值判断结果
        System.out.println(response.isAcknowledged());

    }


    @Test
    public void queryIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        GetIndexRequest getIndexRequest = new GetIndexRequest("test2");
        GetIndexResponse response = indicesClient.get(getIndexRequest, RequestOptions.DEFAULT);

        //获取结果
        Map<String, MappingMetaData> mappings = response.getMappings();
        for (String key:mappings.keySet()){
            System.out.println(key+":"+mappings.get(key).getSourceAsMap());
        }
    }

    @Test
    public void deleteIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        DeleteIndexRequest deleteRequest = new DeleteIndexRequest("test1");
        AcknowledgedResponse response = indicesClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }
    @Test
    public void existIndex() throws IOException {
        //1.使用client获取操作索引的对象
        IndicesClient indicesClient = client.indices();
        GetIndexRequest getIndexRequest = new GetIndexRequest("test1");
        boolean exists = indicesClient.exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);

    }

    @Test
    public void addDoc() throws IOException {
        //数据对象,map
        Map data = new HashMap<>();
        data.put("address","北京大三");
        data.put("name","大三");
        data.put("age",29);
        //1 获取操作文档的对象
        IndexRequest request = new IndexRequest("test2").id("1").source(data);
        //添加数据,获取返回的结果
        IndexResponse re = client.index(request, RequestOptions.DEFAULT);
        System.out.println(re.getId());
    }

    @Test
    public void addDoc1() throws IOException {
        //数据对象,java对象
        Person person = new Person();
        person.setId("2");
        person.setName("大四");
        person.setAddress("台湾省");
        person.setAge(123);
        //将对象转为json
        String data = JSON.toJSONString(person);

        //1 获取操作文档的对象
        IndexRequest request = new IndexRequest("test2").id(person.getId()).source(data,XContentType.JSON);
        //添加数据,获取返回的结果
        IndexResponse re = client.index(request, RequestOptions.DEFAULT);
        System.out.println(re.getId());
    }


    @Test
    public void queryDocById() throws IOException {
        GetRequest getRequest = new GetRequest("test2","1");
        //或者是
//        getRequest.id("1");
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);

        //获取数据对应的json数据
        System.out.println(response.getSourceAsString());
    }
    @Test
    public void delDoc() throws IOException {

        DeleteRequest deleteRequest = new DeleteRequest("test2","1");
        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.getId());
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

?abc!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值